1

我正在开发一个string从文件中读取 a 的 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
4

2 回答 2

1

请在调试器中运行您的程序以了解它正在执行的特定行为。看看它与您的预期有何不同。

gdb可能是最简单的,您可以通过谷歌搜索“gdb cheatsheet”左右开始。记得用-g.

于 2013-03-14T16:56:03.823 回答
0

您应该声明posassize_t而不是intsince std::string::find()returns size_t

此外,当std::string::find()不匹配时,它会返回string::npos而不是-1. 因此,您应该比较posstring::npos不是整数文字-1

于 2013-03-14T17:01:47.377 回答