【问题标题】:Extracting individual value from string using stringstream使用字符串流从字符串中提取单个值
【发布时间】:2015-11-05 07:25:17
【问题描述】:

所以我有 txt 文件 input.txt 我正在读入我的程序。我能够使用getline 函数获取第一行数字,现在我正在尝试获取每个数字。我会将这些数字放入 BST,但我不关心这部分,只关心如何获取每个数字。据我所知,我需要使用 stringstream,但我被困在如何提取每个数字并能够单独添加它们。

BST.cpp

#include "stdafx.h"
#include "BST.h"
#include <iostream>
#include <cstddef>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;


int main()
{
    BST<int> B;
    fstream input;
    input.open("input.txt", ios::in);
    string number;
    stringstream ss;

    if(input.fail())
        cout << "File was not opened successfully" << endl;
    else
        cout<< "File was opened succesffuly" << endl;

    getline(input,number,'\n');
    cout << number << endl;
    ss << number;

    return 0;
}

input.txt

12 6 9 45 3 7 10 2 4 13
4
9
55 18 3 6 78 9
13
66
808 707 909 1001 505 1200 499 644 1190 1592
707
78

【问题讨论】:

  • 只需在循环中使用普通输入运算符&gt;&gt;,就像使用任何其他流(如std::cout)一样。
  • @JoachimPileborg 所以喜欢 ss

标签: c++ stringstream


【解决方案1】:

像这样:

std::string line;
int line_number = 1;
while (std:getline(input, line))
{
    std::cout << "Line #" << line_number++ << ':';

    std::istringstream os(line);

    int number;
    while (os >> number)
        std::cout << ' ' << number;

    std::cout << '\n';
}

对于你输入的前三行,它应该打印出来

第 1 行:12 6 9 45 3 7 10 2 4 13 第 2 行:4 第 3 行:9

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    相关资源
    最近更新 更多