我有一个文本文件的标准读入,但我需要的是一行的前 3 个字符作为 int 读入,该行的其余部分作为字符串逐行读入。我已将示例文本放在下面的代码中。
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char buffer[256];
ifstream myfile ("example.txt");
while (! myfile.eof() )
{
myfile.getline (buffer,100);
cout << buffer << endl;
}
return 0;
}
最佳答案
大概是这样的(伪代码,相信你能看懂真正的操作!)
std::string line;
ifstream myfile ("example.txt");
// this gets a line of text from the file.
while(std::getline(myfile, line))
{
// now you need to extract three characters and convert to int, so is it always guranteed?
if (line.size() > 3)
{
std::string int_s = <substring from 0, size: 3>; // lookup this function in a reference!
std::string rest_s = <substring from 3 to end>; // ditto for the lookup
// now convert the integer part.
long int int_v = <conversion routine, hint: strtol>; // lookup syntax in reference.
// use...
}
}
关于c++将文本文件读入整数和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6016353/