如何在C ++中用逗号分割字符串 [英] how to split a string on comma in C++

查看:1385
本文介绍了如何在C ++中用逗号分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码,用户会输入一个数字,他们想要在数组中的数字。然后是12345,然而约一秒钟后,我意识到这只会工作,如果他们输入数字0-9任何东西在双数字或更多的无法工作。

I have this code currently in which the user would enter a number for how many numbers they want in the array. followed by '12345' however about a second after writing it i realized this would only work if they entered number 0-9 anything in double figures or more wouldnt work.

int numberOfValues;
cout << "Please enter the amount of integers you want in the array" << endl;
cin >> numberOfValues;

int valuesArray[numberOfValues];
string valuesString;

cout << "Please Enter " << numberOfValues << " numbers" << endl;
cin>>valuesString;


for(int i = 0; i < numberOfValues; i++)
{
    valuesArray[i] = valuesString[i];
}
return valuesArray;

我认为最好的方法是让用户输入以逗号分隔的数字然后拆分它们(iv在java中做相同的小porgram,并试图将其改为C + +为​​我自己的个人学习)像在java我使用string.split(,)我想知道是否有任何类似的c ++

im thinking that the best way to do this would be for the user to enter numbers separated by a comma and to split them afterwards (iv done this same little porgram in java and trying to change it to C++ for my own personal learning) like in java i used string.split(",") i was wondering if there is anything similar in c++??

推荐答案

我可以想到的最简单的方法是避免读到一个中间字符串,让cin做工作您:

The simplest way I can think of would be to avoid reading to an intermediate string and let cin do the work for you:

std::vector<int> valuesArray;

int i = 0;
do {
    cin >> i;
    valuesArray.push_back(i);
} while (valuesArray.size() < numberOfValues && cin.get() == ',');

/* edit: You may need to consume a '\n', if you expect one, too: */
do {
    i = cin.get();
} while (i != '\n');

这篇关于如何在C ++中用逗号分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆