C++初学学生,求用简单的语言说明,非常感谢!
一行double带小数点的数字,不定项数量,每个数字之间用不定项个空格隔开,以回车结束输入,放进一个vector里。
比如这样
1.1 2.2 3.3 4.4 5.5 回车
本来是想用cin来跳过空格但是也会跳过回车,如果用cin.get的话得到的是char型,转成double的话小数点后面会丢失。现在的想法就是getline得到一整行,然后一位数一位数地分析,空格丢掉,连在一起的数字重新整合成一个double。
又想了一阵子然后用unget()做到了..不清楚有没有更好一点的办法.
vector<double> v1;
char t;
do //input first line
{
cin.unget();
cin >> count;
v1.push_back(count);
} while ((t=cin.get())!='\n');
初学c++,可能这问题很蠢,但是已经搜索了快两天都不知道怎么解决,求教更简便一点的方法…
Method 1, you can input in multiple lines, with no limit on the number in each line, and whitespace characters (blank lines, spaces, tabs) in the input will be automatically ignored.
Method 2: Enter only one line and automatically ignore whitespace characters (blank lines, spaces, tabs) in the input.
Method three has the same effect as method one.
Note: Replacing
std::cin
in the above method with anystd::istream
type variable or a variable of its subclass has the same effect. For example, change to a variable of typestd::ifstream
to read the file.If other circumstances are not considered:
First use [space] to separate each decimal and put it in a vector<char*>
Convert to double one by one using atof()
Convert one and put it into vector<double>
Optimization:
Parse and convert at the same time, push_back into vector at the same time, all in one loop.
C++ streaming input style
C style input
The above method is suitable for reading from a file, not suitable for console input (because the console cannot know whether you have finished typing)
If it is console input, you can read a whole line first, and then read it one by one Read in:
The implementation is not very elegant, so let’s make do with it.