2

好的,我读到如果我们有一个字符串 s = 1 2 3"

我们可以做的 :

istringstream iss(s);  
int a;
int b;
int c;

iss >> a >> b >> c;

假设我们有一个包含以下内容的文本文件:

测试
1 100 毫秒

测试
2 200 毫秒

测试
3 300 毫秒

ifstream in ("test.txt")
string s;
while (getline(in, s))
{
       // I want to store the integers only to a b and c, How ?
}
4

2 回答 2

0

1)您可以依靠成功转换为 int:

int value;
std::string buffer;
while(std::getline(iss, buffer,' ')) 
{
    if(std::istringstream(buffer) >> value)
    {
        std::cout << value << std::endl;
    }
}

2)或者只是跳过不必要的数据:

int value;
std::string buffer;
while(iss >> buffer) 
{
    iss >> value >> buffer;
    std::cout << value << std::endl;
}
于 2015-01-31T19:09:40.493 回答
0

如果您知道文本文件中详细信息的模式,则可以解析所有详细信息,但只存储 int 值。例如:

ifstream in ("test.txt")
string s;
while (getline(in, s))
{
     getline(in,s); //read the line after 'test'.
     string temp;
     istringstream strm(s);
     s >> temp;
     int a = stoi(temp) // assuming you are using C++11. Else, atoi(temp.c_str())
     s >> temp;
     getline(in,s); // for the line with blank space
}

上面的代码仍然有点不雅。除此之外,您可以做的是在 C++ 中使用随机文件操作。它们允许您移动指针以从文件中读取数据。有关更多信息,请参阅此链接:http: //www.learncpp.com/cpp-tutorial/137-random-file-io/

PS:我没有在我的系统上运行此代码,但我想它应该可以工作。第二种方法确实有效,因为我以前使用过它。

于 2015-01-31T19:11:25.687 回答