Prateek
Prateek

Reputation: 299

strings in c++ run time error

I am working on a c++ program which reads a string from a file. At the end of the string there are some numbers. My task is to display the nth number from the end of the string .

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

Upvotes: 1

Views: 1070

Answers (2)

timrau
timrau

Reputation: 23058

You should declare pos as size_t instead of int since std::string::find() returns size_t.

Also, when std::string::find() matches nothing, it returns string::npos instead of -1. Thus, you should compare pos against string::npos instead of the integer literal -1.

Upvotes: 0

djechlin
djechlin

Reputation: 60778

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. Remember to compile with -g.

Upvotes: 1

Related Questions