簡體   English   中英

C ++運行時錯誤中的字符串

[英]strings in c++ run time error

我正在研究從文件讀取string的c ++程序。 string的末尾有一些數字。 我的任務是顯示字符串末尾的nth數字。

這是我的代碼。 該程序接受文件的路徑:

#include<iostream>
#include<fstream>
#include<string>
#include<stdlib.h>

using namespace std;

int main(int argc,char** argv)
{
    ifstream file;
    int num,i=0,pos;    
    std::string lineBuffer;
    file.open(argv[1],ios::in) ;  
    while (!file.eof()) 
      {
         getline(file, lineBuffer);        
         if (lineBuffer.length() == 0)
              continue; //ignore all empty lines
         else 
           {
             pos=0;            
            std::string str1("");
            std::string str2("");
            std::string final("");
            std::string number("");
            std::string output("");
                while(pos!=(-1))
                {
                  pos=lineBuffer.find(" ");                               
                  str2=lineBuffer.substr(0,1);
                  lineBuffer=lineBuffer.substr(pos+1);
                  final+=str2;
                  i++;
                }
                number=final.substr((i-1));
                num=atoi(number.c_str());
                output=final.substr(i-(num+1),1);
                cout<<output;                            
           }    
      }
      file.close();
       return 0;
}

我的程序為文件的第一行提供了正確的輸出。 但是之后,這給了我一個運行時錯誤。 我不知道為什么會這樣。

我要發送到終端的文件包含:

a b c d 4
b e f g 2

請在調試器中運行程序,以了解其正在執行的特定行為。 查看它與您期望的差異。

gdb可能是最簡單的,您可以通過谷歌搜索“ gdb速查表”左右開始。 記得用-g編譯。

您應該將pos聲明為size_t而不是int因為std::string::find()返回size_t

另外,當std::string::find()匹配時,它返回string::npos而不是-1 因此,您應該將posstring::npos進行比較,而不是比較整數-1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM