大家早上好:)
我用 C++ 编写了一段代码,可以从 txt 文件中读取信息。它获取第一行中的信息,将其保存在一个字符串中,然后我想使用这些信息。我想读这个字符串,当它找到一个“|”字符它必须跳到一个新行。这很简单,但是我在执行时遇到了问题,我已经尝试了几个小时来寻找问题,但我没有成功。 :( 我附上了代码。
预先感谢您的帮助。
#include <string>
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
ifstream ifs( "C:\\a\\text.txt" );
string temp;
getline( ifs, temp );
cout<<temp<<endl;
string * pch;
pch = strtok (temp,"|");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, "|");
}
system("pause");
return 0;
}
最佳答案
strtok 使用 char*,而不是 string*。这可能就是您遇到问题的原因。
由于您是用 C++ 实现的,我建议您使用字符串函数而不是 strtok:
int main()
{
ifstream ifs( "C:\\a\\text.txt" );
string temp;
getline( ifs, temp );
cout<<temp<<endl;
size_t tokenPos = temp.find("|");
while (tokenPos != string::npos)
{
cout << temp.substr(0, tokenPos) << endl;
temp.erase(0, tokenPos+1);
tokenPos = temp.find("|");
}
system("pause");
return 0;
}
要将您的文本存储在您在评论中描述的值中,您需要执行以下操作:
int main()
{
ifstream ifs( "C:\\a\\text.txt" );
int id;
int type;
int columns;
string temp;
getline( ifs, temp );
cout<<temp<<endl;
size_t tokenPos = temp.find("|");
while (tokenPos != string::npos)
{
int i=0;
tokenPos = temp.find("|");
cout << temp.substr(0, tokenPos) << endl;
if(i==0)
{
id = atoi(temp.substr(0, tokenPos).c_str());
}
else if(i==1)
{
type = atoi(temp.substr(0, tokenPos).c_str());
}
else if(i==2)
{
columns = atoi(temp.substr(0, tokenPos).c_str());
}
++i;
temp.erase(0, tokenPos+1);
}
cout << "ID: " << id << ", Type: " << type << ", Columns: " << columns << endl;
system("pause");
return 0;
}
关于c++ - 使用strtok函数时出现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4920424/