C++ 蒸汽管道破裂

C++ 蒸汽管道破裂,c++,istringstream,C++,Istringstream,好的,我读到了,如果我们有一个字符串s=“1 2 3” 我们可以做到: istringstream iss(s); int a; int b; int c; iss >> a >> b >> c; 假设我们有一个包含以下内容的文本文件: 测试1 100毫秒 测试2 200毫秒 测试3 300毫秒 1) 您可以依靠成功转换为int: int value; std::string buffer; while(std::getline(iss, buffer

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

我们可以做到:

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

iss >> a >> b >> c;
假设我们有一个包含以下内容的文本文件:

测试1
100毫秒

测试2
200毫秒

测试3
300毫秒

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

int value;
std::string buffer;
while(std::getline(iss, buffer,' ')) 
{
    if(std::istringstream(buffer) >> value)
    {
        std::cout << value << std::endl;
    }
}
int值;
字符串缓冲区;
而(std::getline(iss,buffer,'))
{
if(std::istringstream(缓冲区)>>值)
{
std::cout缓冲区)
{
iss>>值>>缓冲区;

std::cout如果您知道文本文件中细节的模式,您可以解析所有细节,但只存储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++,我们还可以使用随机文件操作。它们允许您移动指针来从文件读取数据。请参阅此链接获得更多信息:


PS:我还没有在我的系统上运行这段代码,但我想它应该可以工作。第二种方法确实可以工作,就像我以前使用过的一样。

1st方法成功地打印了整数值,但是如何将它们解析为int a、int b和int c,因为它们只存储在“int value”中根据代码!@TharwatHarakeh,您可以将它们存储在动态数组
std::vector v;
中,而不是
std::cout您可以为它提供完整的工作代码吗?我尝试了您所说的,但无法使其工作代码:下面是一个错误,看起来您的输入文件少于3个整数,当您尝试调用
v[2]
,例如,没有这样的元素
int value;
std::string buffer;
while(iss >> buffer) 
{
    iss >> value >> buffer;
    std::cout << value << std::endl;
}
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
}