2017-10-18 383 views
0

我想創建一個獲取用戶輸入到類型字符串數組的程序,但是因爲我不知道用戶要放多少物品在,我要創建數組空的,因爲我知道,所以當我試圖創建一個帶有錯誤出現在任何初始值陣列如何在C++中定義一個沒有大小初始值的數組

錯誤:Error's Image

LNK2001 unresolved external symbol "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > * listOfItems" ([email protected]@[email protected][email protected]@[email protected]@[email protected]@[email protected]@[email protected]@A) 

這裏的形象代碼 CODE

#include "stdafx.h" 
#include <iostream> 
#include <string> 

std::string listOfItems[]; 

void getInfoToArray() 
{ 
    for (int i = 0;; i++) 
    { 
     //Get the info of the array. 
     std::cin >> listOfItems[i]; 

     //Check if the user input is -1. 
     if (listOfItems[i] == "-1") break; 
    } 
} 

int main() 
{ 
    getInfoToArray(); 
    return 0; 
} 

如果有人比試圖創建一個空數組有更好的解決方案,我會很感激。

+5

使用std :: vector的,而不是發表評論。 –

+3

https://i.imgur.com/5r143L6.png – melpomene

+0

謝謝弗拉德,我該如何評價你的回答? – Nomade040

回答

0

正如評論中的建議,嘗試使用std :: vector來代替。

但是,如果您確實想要使用數組,您必須事先定義數組的大小。

您可以使用新命令並在運行時動態設置數組的大小。

// Example program 
#include <iostream> 
#include <string> 

std::string *listOfItems; 

void getInfoToArray(int n) 
{ 
    listOfItems = new std::string[n]; 
    for (int i = 0;i<n; i++) 
    { 
     //Get the info of the array. 
     std::cin >> listOfItems[i]; 

     //Check if the user input is -1. 
     if (listOfItems[i] == "-1") break; 
    } 
} 

int main() 
{ 

// getInfoToArray(); 
    int size; 
    std::cout<<"enter size of array" 
    std::cin >> size; 
     getInfoToArray(size); 
    for(int i=0;i<size;i++){ 
     std::cout<<listOfItems[i]<<" "; 
    } 
    return 0; 
} 

另一種不從用戶那裏獲取輸入的方法是設置預定義的最大尺寸。這是靜態分配,編譯時間。類似的,

// Example program 
#include <iostream> 
#include <string> 

std::string listOfItems[10]; 

void getInfoToArray() 
{ 
    for (int i = 0;; i++) 
    { 
     //Get the info of the array. 
     std::cin >> listOfItems[i]; 

     //Check if the user input is -1. 
     if (listOfItems[i] == "-1" && i<9) break; 
    } 
} 

int main() 
{ 
     getInfoToArray(); 
    return 0; 
} 

這都是因爲內存是在數組的開始分配的,除非你使用了一個指針。

請隨時免費的,如果您有任何疑問

相關問題