我正在开发一个从文件中读取 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/