想要使用sstream解析int类型的字符串输入
want to parse string input for int using sstream
我是c++编程新手。我读过如何解析可以在SO问题中使用向量(Int标记器)。但我已经尝试了以下数组。我只能从字符串中解析一个数字。如果输入字符串为"11 22 33等"
#include<iostream>
#include<iterator>
#include<vector>
#include<sstream>
using namespace std;
int main()
{
int i=0;
string s;
cout<<"enter the string of numbers n";
cin>>s;
stringstream ss(s);
int j;
int a[10];
while(ss>>j)
{
a[i]=j;
i++;
}
for(int k=0;k<10;k++)
{
cout<<"t"<<a[k]<<endl;
}
}
如果我输入"11 22 33"
output
11
and some garbage values.
如果我已经初始化stringstream ss("11 22 33");
,那么它的工作很好。我做错了什么?
问题是:
cin>>s;
将一个空格分隔的单词读入s,因此s只有11。
你想要的是:
std::getline(std::cin, s);
或者您可以直接从std::cin
while(std::cin >> j) // Read a number from the standard input.
似乎cin>>s
停止在第一个空白。试试这个:
cout << "enter the string of numbers" << endl;
int j = -1;
vector<int> a;
while (cin>>j) a.push_back(j);
We can use cin to get strings with the extraction operator (>>) as we do with fundamental data type variables
cin >> mystring;
However, as it has been said, cin extraction stops reading as soon as if finds any blank space character, so in this case we will be able to get just one word for each extraction.
必须使用getline()
string s;
cout<<"enter the string of numbers n";
getline(cin, s);
相关文章:
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 类型字符串::长度()。我得到了"Unable to resolve identifier length"
- 如何掩盖对象数组的数据类型字符串到C 中的INT
- 解析参数值 - 字符串和链接值(类型字符串的链接值)与(特定类型的)变量
- C 中的枚举类型字符串类别
- 与基本面作斗争.特别是字符[],字符*和从数组中读取.也许我应该使用类型字符串
- 矢量类型 字符串,但当用整数初始化时
- 如何从const char *类型字符串中删除新线字符
- 在 c++ 中将 ostream 分配给数据类型字符串
- Linux 编译错误 - 无法将类型"字符串"转换为类型"字符串&&"
- LPCSTR 类型字符串出现乱码或显示错误
- C 表达式必须具有类型 - 字符串到const char*
- 将值分配给字符类型字符串
- 将组合框中的类型字符串与其项目进行比较
- 如何将返回类型字符串的数据复制到C++中
- 如何处理csv文件输入流,我需要将文件的每一行中的数据划分为6个不同的变量(类型字符串和int)
- 自定义C类型字符串类的问题
- 在c++中创建自定义C类型字符串类
- 在读取.csv时将数组类型字符串转换为double
- C++将类型字符串变量中的单词转换为小写