istringsteam与换行符

时间:2015-01-31 18:48:58

标签: c++ istringstream

好的,我读过如果我们有一个字符串s =“1 2 3”

我们可以做到:

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

iss >> a >> b >> c;

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

TEST1
100毫秒

TEST2
200毫秒

TEST3
300毫秒

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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:我没有在我的系统上运行此代码,但我想它应该可行。第二种方法可以肯定,因为我之前使用过它。

相关问题