【发布时间】:2013-03-14 16:49:05
【问题描述】:
我正在开发一个从文件中读取 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
【问题讨论】:
-
操作系统是什么?
-
首先你应该在调试器中运行你的程序。这会告诉你错误在哪里。它还可以让您检查变量,因此您可能能够找出导致错误的是什么。
-
while (!file.eof()) {已损坏,eof()在尝试读取 之后 之前不会返回 true,因此您有一个错误。 far 最好写:while(getline(file, lineBuffer)) { -
除了你的具体问题,我认为@Evan 解决了,我建议你使用 stringstreams 解决这个问题。