我正在从一个文件读取string
C++程序工作。在string
的末尾有一些数字。我的任务是显示字符串末尾的nth
数字。字符串在c + +运行时错误
这是我的代码。该程序接受文件的路径:
#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
什么是操作系统? – 2013-03-14 16:51:27
什么是错误? – 2013-03-14 16:51:52
首先,您应该在调试器中运行您的程序。这会告诉你_哪里错误是。它也可以让你检查变量,所以你可能会发现_what_会导致错误。 – 2013-03-14 16:52:09