簡體   English   中英

使用stringstream從字符串中提取單個值

[英]Extracting individual value from string using stringstream

因此,我有要讀取到程序中的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

像這樣:

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';
}

輸入的前三行應顯示

Line #1: 12 6 9 45 3 7 10 2 4 13
Line #2: 4
Line #3: 9

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM