C++字符串遇到的输入,循环输入,一行两个字符串连续输入n行
程序员文章站
2022-08-11 08:06:32
单独一行的输入#include #include using namespace std; int main(){//对于char* / char[]char s[1001];cout<<"Please input char[]:"<
单独一行的输入
#include <iostream>
#include <string>
using namespace std;
int main()
{
//对于char* / char[]
char s[1001];
cout<<"Please input char[]:"<<endl;
cin.getline(s, 1000);//iostream下的函数, 第二个参数表示允许的最大输入长度
cout<<"Output:"<<endl<<s<<endl<<strlen(s)<<endl;
//对于string
string ss;
cout<<"Please input string:"<<endl;
getline(cin, ss); //这个getline函数在<string>头文件下
cout<<"Output:"<<endl<<ss<<endl<<ss.length()<<endl;
return 0;
}
循环输入一组后,再循环输入一组
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int t1, t2, r;
vector<int> x, y;
cout << "请输入x的值" << endl;
while (cin >> t1, t1) {
x.push_back(t1);
}
cout << "请输入y的值" << endl;
while (cin >> t2, t2){
y.push_back(t2);
}
cout << "请输入r的值" << endl;
cin >> r;
for (int i = 0; i < y.size(); i++)
cout << y[i] << " ";
cout << "\nr=" << r << endl;
return 0;
}
一行两个字符串,连续输入n行
#include <iostream>
#include<string>
#include<vector>
#include<utility>
using namespace std;
int main()
{
int n;
string A, B;
vector<pair<string, string>> city;
cin >> n;
cin.get();
while (n--) {
getline(cin, A, ' ');//遇到空格停止,读取第一个字符串串
getline(cin, B, '\n');//遇到换行停止,此时读取了第二个字符串
city.push_back(pair<string, string>(A, B));
}
}
或者
int main()
{
int n;
string A, B;
vector<pair<string, string>> city;
cin >> n;
while (n--) {
cin >> A >> B;
city.push_back(pair<string, string>(A, B));
}
}
输入:
Beijing Nanjing
Nanjing Guangzhou
本文地址:https://blog.csdn.net/weixin_44210987/article/details/108185476
上一篇: Android社招面试题整理
下一篇: 朋友们,你收入多少