简体   繁体   English

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

[英]strings in c++ run time error

I am working on a c++ program which reads a string from a file. 我正在研究从文件读取string的c ++程序。 At the end of the string there are some numbers. string的末尾有一些数字。 My task is to display the nth number from the end of the string . 我的任务是显示字符串末尾的nth数字。

Here is my code. 这是我的代码。 The program accepts a path to a file: 该程序接受文件的路径:

#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;
}

My program gives the correct output for first line in the file. 我的程序为文件的第一行提供了正确的输出。 But after that it's giving me a runtime error. 但是之后,这给了我一个运行时错误。 I don't know why is this happening. 我不知道为什么会这样。

The file I'm sending to the terminal contains: 我要发送到终端的文件包含:

a b c d 4
b e f g 2

Please run your program in a debugger to understand the specific behavior it is doing. 请在调试器中运行程序,以了解其正在执行的特定行为。 See where it diverges from what you are expecting. 查看它与您期望的差异。

gdb may be simplest and you can get started by Googling "gdb cheatsheet" or so. gdb可能是最简单的,您可以通过谷歌搜索“ gdb速查表”左右开始。 Remember to compile with -g . 记得用-g编译。

You should declare pos as size_t instead of int since std::string::find() returns size_t . 您应该将pos声明为size_t而不是int因为std::string::find()返回size_t

Also, when std::string::find() matches nothing, it returns string::npos instead of -1 . 另外,当std::string::find()匹配时,它返回string::npos而不是-1 Thus, you should compare pos against string::npos instead of the integer literal -1 . 因此,您应该将posstring::npos进行比较,而不是比较整数-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM