第一种方法:规定数据大小的多少
#include <iostream>
using namespace std;int main()
{//这样即可 将 多个字符保存于 一个 数组中,可以为多个字符串来保存也可以用多个字符来保存// //这里就是满足的 hello my world// 然后 满足于 s[0]=hello // s[1]=my s[2]= world//不够这个方法需要预先规定其大小,所以还需升级 string s[100]; //string可换为 char 或 int 等 char ch;int i=0;cout<<"请输入字符串以空格或tab隔开"<<endl; while(cin>>s[i]){i++;if(ch=getchar()=='\n') //getchar() 保存输入的字符并和 \n比较 {cout<<"end"<<endl;break;}}for(int j=0;j<i;j++){cout<<s[j]<<endl;} }
第二种方法:不固定大小(这样就比较灵活),当然输入的string类型进行了固定,若需要int类型,则之后将其转换为int即可
#include <iostream>
using namespace std;
#include <sstream>
#include <vector>
#include <string>
//读取一行字符串然后 知道 换行符的时候则走向结束
//如 getline() 便是以空格进行分割,然后以换行符进行结束int main()
{//如何将一串字符 以空格分开 //如 hello my world//保存为 s[0]=hello s[1]=my s[2]=world// string str;getline(cin,str); //输入字符串 hello my world vector<string> arr;istringstream cuts(str); //istringstream 可以分割tab,空格,回车换行符的字符串 string word;while(cuts>>word){arr.push_back(word);}//若是不需要转换为int类型,则上方代码即可满足,//下方的则是将string类型的 数字转换为 int类型,且将其插入到 nums数组中 // 其转换的方式,可以类比于 int类型转换为 string 等// 其 也就是将 int a 变成其他类型即可vector<int> nums;int a;for(int i=0;i<arr.size();i++){stringstream sx;sx<<arr[i]; //将字符类型转换为流sx>>a;nums.push_back(a); //将转换后的数字压入数组中
// cout<<arr[i]<<endl;}cout<<nums[2]<<endl;//将字符串类型的转为 整型
// stringstream sx; //定义流
// sx<<arr[0]; //将字符类型转换为流 sx
// int abc;
// sx>>abc; //将流转换为 int 类型
// cout<<abc<<endl;
// int sum = abc+1000;
// cout<<"sum::"<<sum<<endl;
}