我有以下代码从 txt 文件中读取输入,如下所示
Paris,Juli,5,3,6
Paris,John,24,2
Canberra,John,4,3
London,Mary,29,4,1,2
我的代码是将数据加载到 map 中,然后我想打印 map 内容以确保它已被正确插入,我检查了 m 的值,因为它在拆分线时使用了它。但是,在执行过程中,我将其继续为 0,这意味着它永远不会进入 while 循环。我以前使用过这部分代码并且它有效。我找不到哪里出错了。
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>
#include<map>
using namespace std;
struct info {
string Name;
int places;// i will use the binary value to identfy the visited places example 29 is 100101
// this means he visited three places (London,LA,Rome)
vector<int> times; // will represent the visiting time,e.g. 1,2,5 means london 1 time, LA
// twice and Rome five times
};
map<string,vector<info> > log;
map<string,vector<info> >::iterator i;
fstream out;
int main() {
out.open("log.txt", std::ios::in | std::ios::out | std::ios::app);
string line;
char* pt;
string temp[19];
// for each line in the file
while (!out.eof())
{
getline(out,line);//read line from the file
pt=strtok(&line[0],"," );//split the line
int m=0;
while (pt != NULL)
{
temp[m++] = pt; // save the line info to the array
cout<<m<<" ";
pt = strtok (NULL, ",");
}
cout<<m<<" "; // during the execution I get this as continues 0s which means it is never enter the while loop
info tmp;
// read the other data
tmp.Name=temp[1];
tmp.places=atoi(temp[2].c_str());
for ( int i=3;i<=m;i++)
{
tmp.times.push_back(atoi(temp[i].c_str()));
}
// create a new object
log[temp[0]].push_back(tmp);
}
vector<int>::iterator j;
for(i=log.begin();i!=log.end();i++) {
cout<< "From "<< i->first<<" city people who travels: "<<endl;
for (size_t tt = 0; tt < (i->second).size(); tt++) {
cout<< (i->second[tt]).Name<< " went to distnations "<< (i->second)[tt].places<<" \nwith the folloing number of visiting time ";
for (j=((i->second[tt]).times).begin();j!= ((i->second[tt]).times).end();j++)
cout<<*j<<" ";
}
}
system("PAUSE");
return 0;
}
最佳答案
这是一个错误
// for each line in the file
while (!out.eof())
{
getline(out,line);//read line from the file
应该是
// for each line in the file
while (getline(out,line))
{
坦率地说,我发现这个错误重复出现的频率令人难以置信。 eof
并不像您认为的那样。它测试 last 读取是否因文件结尾而失败。您正在使用它来尝试预测下一次读取是否会失败。它根本不是那样工作的。
这一行是错误的
pt=strtok(&line[0],"," );//split the line
strtok
适用于 C 字符串,不能保证它适用于 std::string
。
但这些都不太可能是您真正的错误。我建议仅使用 ios::in
打开文件。毕竟你只想从中读取。
关于c++ - 读取文件并在 C++ 中拆分行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12932591/