1. 多行字符串变量,中间有逗号隔开
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
/*
多行字符串变量,中间有逗号隔开
123, ad, ada, da
dad,da, ad, dad
*/
int main(){
string input;
vector<vector<string>> res;
for(int i = 0; i < 3; i++){
string str;
vector<string> vec;
getline(cin, input);
stringstream ss(input);
while(getline(ss, str, ',')){
vec.push_back(str);
}
for(auto &str: vec){
cout << str << " ";
}
cout << endl;
res.push_back(vec);
}
for(int i = 0; i < res.size(); i++){
for(int j = 0; j < res[i].size(); j++){
cout << res[i][j] << " ";
}
cout << endl;
}
system("pause");
return 0;
}
2. 整型和字符串组合,如AAA,3
#include<iostream>
#include<vector>
#include<string>
using namespace std;
// 整型和字符串组合,AAA,3
int main(){
string s;
vector<char> vec;
char n;
getline(cin, s);
for (int i = 0; i < s.size(); i++){
if(s[i] == ','){
n = s[i + 1];
break;
}
vec.push_back(s[i]); // 如果没有指定vec长度,就不能用vec[i] = s[i];
}
string res;
for(int i = 0; i < vec.size(); i++){
res = res + vec[i];
}
cout << res << endl;
// string s;
// int n;
// char tmp;
// cin >> s >> tmp >> n; 这种方法不行,s会一直接收cin的数据,直至换行,下一行数据才能被tmp接收
// cout << "s = " << s << "tmp = " << tmp << "n = " << n << endl;
return 0;
}
3. 多行整型变量,中间没有逗号隔开
#include<iostream>
#include<vector>
#include<string>
// 多行整型变量,中间没有逗号隔开
using namespace std;
int main()
{
int n;
cin >> n;
string s;
vector<vector<int>> vec;
for(int i = 0; i < n; i++){
vector<int> nums;
int num;
while(cin >> num){
nums.push_back(num);
if(getchar() == '/n') break;
}
vec.push_back(nums);
}
// int count = 0;
// int maxNum = 0;
// for(int i = 0; i < vec.size(); i++){
// maxNum = max(maxNum, vec[i][0]);
// }
// for(int j = 0; j < vec.size(); j++){
// if(maxNum <= vec[j][1]) count++;
// }
// cout << count << endl;
cout <<"输出vec: " << endl;
for(int i = 0; i < vec.size(); i++){
cout << vec[i][0] <<" "<< vec[i][1] << endl;
}
return 0;
}
4. 整型变量+',' + 字符串+',' + 字符串
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
using namespace std;
// 整型变量+',' + 字符串+',' + 字符串
int main(){
string str;
int n;
char tmp;
cin >> n >> tmp; // 输入为 1,abc,ada n自动匹配到1,tmp自动匹配到',' ?
string input;
getline(cin, input);
stringstream ss(input);
vector<string> vec;
while(getline(ss, str, ',')){
vec.push_back(str);
}
cout <<"n = " << n << endl;
for(auto &str: vec){
cout << str << " ";
}
cout << endl;
return 0;
}