c++ - C++运行时错误中的字符串

标签 c++ string file

我正在开发一个从文件中读取 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 cheatsheet”左右开始。记得用-g编译。

关于c++ - C++运行时错误中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15415349/

相关文章:

ruby-on-rails - 文件测试存在吗? ruby on rails 问题

c++ - 断言 `str' 失败

c++ 返回不同的结果

c++ - C++逐行读取文本文件

c++ - 让主程序知道资源在哪里(图像、数据……)

c# - 将字符串从 C++/CLI 类库传递到 C#

c++ - 在C++中将字符串转换为整数

将字符串数组中的每个单词大写

java - 与 Whatsapp 共享音频文件(文件格式不支持错误)

提交帖子表单时Android Webview下载文件