2017-07-17 165 views
0

我想創建一個while循環,只要從文件中取出的字符串不是空的就運行。我需要用空格分隔字符串並保存信息以供將來使用,所以我將子字符串放入數組中,然後將其從實際數組中移除。但是,當我運行該程序時,我不斷收到錯誤消息,或者只是打印出空白區域。 I added a picture of the file I'm using and of the error message I'm getting子串和擦除

fstream myfile; 
string line; 
string info[10000]; 
int i=0, pos; 

myfile.open("bfine_project1_input.txt"); 
//Check 
if (myfile.fail()){ 
    cerr << "Error opening file" << endl; 
    exit(1); 
} 

if (myfile.is_open()){ 
    while (getline (myfile,line)){ 
     while(line.size() !=0){ 
      pos = line.find(" "); 
      info[i]= line.substr(0,pos); 
      i++; 
      cout << info[i] << endl; 
      //line.erase(0, pos); 
     } 
    } 
} 
+0

是info' vector'?如果是這樣,它的大小適當嗎? – GWW

+0

info是一個數組 – cdecaro

+1

如何聲明信息?我如何申報?我在哪裏分配?你收到什麼錯誤信息?爲什麼SO需要[mcve]? –

回答

0

有兩個問題我可以看到。

1 - 你增加「我」在打印之前(您存儲在信息值[0]和打印信息[1])

2日 - 刪除您使用不會刪除空格「」的方式,所以find(「」)會從第二次向前返回位置0。

一些調整可以解決這個問題。請參閱下面的代碼:

重要提示:您的代碼寫入方式需要在行末加空格!

string line; 
string info[10000]; 
int i=0, pos; 

line = "1325356 134 14351 5153613 1551 "; 
while(line.size() !=0){ 
    pos = line.find(" "); 
    info[i]= line.substr(0, pos); 
    cout << i << " " << info[i] << endl; 
    line.erase(0,pos+1); //ERASE " " too! 
    i++;//increment i only after everything is done! 
}