【问题标题】:how to parse integers from input with commas如何用逗号解析输入中的整数
【发布时间】:2020-06-25 02:14:18
【问题描述】:

我正在尝试弄清楚如何将整数提取到 int 向量中,以便我可以计算它们:

输入 = 40,50,29,50

*取出分隔符,将数字分隔成一个数组

arr[ ] = {40 50 29 50}

arr[0]+arr[1] = 90

如果没有 std:: 我会喜欢它(又名 using namespace std;我更容易理解)

这里有人举了一个例子,但如果它是同一件事或者如何真正理解它,我没有。还有一个使用令牌的建议,但我也不确定如何执行此操作。有什么帮助谢谢!

【问题讨论】:

  • 拜托,拜托,请在互联网上搜索“C++ 读取文件逗号分隔”。那里已经有很多例子了。在发布到 StackOverflow 之前始终搜索互联网。如果您的代码有问题,请发布minimal reproducible example 并将标题更改为“无法从 CSV 文件读取整数”;表明我们应该检查您的代码。
  • '我会喜欢没有 std' 意识到使用命名空间 std; 键入实际上是编程中的一个坏习惯,尽管它确实有助于提高可读性。
  • 也许您可以更改 cin 的分隔符 (stackoverflow.com/questions/7302996/…) 并像使用空格分隔一样正常读取它们。 :)

标签: c++ token clion


【解决方案1】:

您可以将整个输入存储为string,然后循环遍历它并将逗号之间的子字符串转换为整数:

#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <vector>

using namespace std;

int main(){
    vector <int> nums;

    string str;
    cin >> str;

    int lastcomma = -1;
    while(str.find(',', lastcomma+1) != string::npos){ // find the next comma
        int curr = str.find(',', lastcomma+1);

        // stoi converts a string to an integer; just what you need
        nums.push_back(stoi(str.substr(lastcomma+1, curr - (lastcomma+1))));

        lastcomma = curr;
    }
    
    // get the last number
    nums.push_back(stoi(str.substr(lastcomma+1, str.size()-(lastcomma+1))));
  

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多