我正在使用Qt 5.2.1,这是我想在程序中使用的功能的一部分-
while( getline(in,str,':')
{
getline(str,'\n');
int var = atoi(str.c_str());
}
我的问题是如何在qt中实现呢?
我搜索了一下文档,发现了关于readline和split的信息,但我不知道如何使用它们
任何帮助深表感谢。 :D
编辑-我的第一个getline在文本文件中检查':',第二个getline提取数字(在':'之后)并将其转换为整数并将其存储在变量中。
2编辑:
这是我的文本文件的外观...
500-1000:1
1000-1500:2
1500-2000:7
2000-2500:6
1,2,7,6是我程序中需要的值
最佳答案
我不确定您要做什么。如果您尝试读取文件:
QFile file("/path/to/file.whatever");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text) {
// error message here
return;
end
while (!file.atEnd()) {
QString line = in.readLine();
// now, line will be a string of the whole line, if you're trying to read a CSV or something, you can split the string
QStringList list = line.split(",");
// process the line here
}
QFile
超出范围时将自行关闭。如果您尝试根据已有的
:
分隔符来分割字符串,请使用:QStringList list = line.split(":");
编辑:
既然您已经定义了要执行的操作(读取类似“ value:integer”之类的内容),则可以轻松地使用QStringList进行此操作。例:
QString input = "value:1";
QStringList tokens = input.split(":");
int second = tokens.at(1).toInt();
当然,您需要使用自己的错误检查,但这只是我认为您要尝试执行的一个示例。