C++ 输入输出的格式问题
示例1:
输入一行整数,每个整数之间用一个或多个空格隔开,输入回车结束输入。
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec;
do {
int num = 0;
cin >> num;
vec.push_back(num);
} while(cin.get() != '\n');
for(auto num : vec) {
cout << num << endl;
}
return 0;
}
示例2:
输入一行字符串,字符串中可以用空格,输入回车结束输入。
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
getline(cin, str);
cout << str << endl;
return 0;
}
示例3
输入字符串,各字符串之间以空格隔开,以回车结束输入
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> vec;
do {
string str;
cin >> str;
vec.push_back(str);
} while(cin.get() != '\n');
for(auto str : vec) {
cout << str << endl;
}
return 0;
}
示例4
给定一个字符串,提取其中的“单词”
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
string str;
getline(cin, str);
int h1 = 0, h2 = 0;
vector<string> vec;
do {
while(h1 < str.size() && str[h1] == ' ') h1++;
h2 = h1;
while(h2 < str.size() && str[h2] != ' ') h2++;
string tmp(str.begin()+h1, str.begin()+h2);
vec.push_back(tmp);
h1 = h2;
} while(h1 < str.size());
for(auto str : vec) {
cout << str << endl;
}
return 0;
}
vector<string> vec;
string str;
while(cin >> str) {
vec.push_back(str);
}
示例5
将一串数字输出,数字之间有空格,开头和结尾没有空格
/*
for(int i = 0;i < res.size();i++) {
i < res.size()-1 ? cout << res[i] << " " : cout << res[i];
}
*/
for(int i = 0;i < res.size();i++) {
cout << res[i];
i < res.size()-1 && cout << " ";
}
for(int i = 0;i < 6;i++) {
cout << a[i];
i == 5 ? cout << endl : cout << ' ';
}
for(int i = 0;i < vec.size();i++) {
cout << vec[i];
i == vec.size()-1 ? cout << endl : cout << ' ';
}
示例6
以EOF结尾,即文件结束符。
这种处理方式适用于以文件作为输入,或者在键盘手动输入文件结束符作为结尾标记。
int n;
while(cin>>n)
{
//处理输入的合法值。
}
在windows上输入EOF的方法为Ctrl+Z
其它平台上输入EOF的方法为Ctrl+D
示例7
将栈中的元素从栈顶到栈底依次输出,中间有空格,结尾是换行。
链接:https://www.nowcoder.com/questionTerminal/ee5de2e7c45a46a090c1ced2fdc62355?toCommentId=1593971
来源:牛客网
while(!st.empty()) {
cout << st.top();
st.pop();
st.empty() ? cout << endl : cout << ' ';
}