如何在C ++中读取两位数和一位数字

问题描述 投票:-1回答:2

我有一个问题,使我的C ++程序无法读取两位数的整数。我的想法是将其读取为字符串,然后以某种方式将其解析为单独的整数,然后将其插入到数组中,但是我一直坚持让代码正确读取数字。

样本输出:

 i: 0 codeColumn 0

 i: 1 codeColumn 1

 i: 2 codeColumn 0 0

 i: 3 codeColumn 0

 i: 4 codeColumn 31 0

 i: 5 codeColumn 1

 i: 6 codeColumn 43 0

 i: 7 codeColumn 3

 i: 8 codeColumn 9 0

所以该文件基本上是由逗号分隔的三行的行:

0,1,0 0,0,31 0,0,18 0,0,8 0,11,0

我的问题是,如何获取尾随零(请参见上文)以移动到新行?我尝试使用“ char”和一堆if语句将单个数字连接成两位数字,但是我觉得那不是很有效或不理想。有什么想法吗?

我的代码:

#include <iostream>     // Basic I/O
#include <string>       // string classes
#include <fstream>      // file stream classes
#include <sstream>
#include <vector>

int main()
{

    ifstream fCode;
    fCode.open("code.txt"); 
    vector<string> codeColumn;

    while (getline(fCode, codeLine, ',')) {
        codeColumn.push_back(codeLine);
    }

    for (size_t i = 0; i < codeColumn.size(); ++i) {

                cout << " i: " << i << " codeColumn " << codeColumn[i] << endl;

    }

    fCode.close();

}
c++ double text-files digits delimited-text
2个回答
0
投票
getline(fCode, codeLine, ',')

将在逗号之间阅读,因此0,1,0 0,0,31将完全按照您所见的拆分。

0,1,0 0,0,31
 ^ ^   ^ ^

收集的令牌是^ s之间的所有内容>

您有两个定界符,需要考虑逗号和空格。处理空间最简单的方法是使用哑巴>>

std::string triplet;
while (fCode >> triplet)
{
    // do stuff with triplet. Maybe something like      
    std::istringstream strm(triplet); // make a stream out of the triplet
    int a;
    int b; 
    int c;
    char sep1;
    char sep2;
    while (strm >> a >> sep1 >> b >> sep2 >> c // read all the tokens we want from triplet 
           && sep1 == sep2 == ',') // and the separators are commas. Triplet is valid
    {
       // do something with a, b, and c
    }
}

Documentation for std::istringstream


0
投票

因此,我将向您展示3种解决方案,从易于理解的C-Style代码开始,然后从使用std::istringstream库和迭代器的更现代的C ++代码开始,最后是面向对象的C ++解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.