C++ 输入空格隔开的一行数,到回车换行中止
时间: 2023-06-10 15:03:03 浏览: 94
好的,您的问题是关于输入空格隔开的一行数,到回车换行中止。为了回答您的问题,您可以使用如下代码来实现:
```c
#include <stdio.h>
int main() {
int num;
/* 使用scanf函数读取输入 */
while (scanf("%d", &num) != EOF) {
printf("%d ", num);
}
return 0;
}
```
这段代码中,我们使用了`scanf`函数来读取输入,`%d`表示读取一个整数,读取的结果会放到`num`变量中。然后我们使用`printf`函数将读取到的整数打印输出,同时输出一个空格来分隔不同的数值。
当输入结束时,`scanf`函数会返回`EOF`(或者在Windows系统中是-1),此时循环结束,程序也就结束了。
相关问题
c++输出集合set所有元素,中间空格隔开,末尾换行
由于集合中的元素是无序的,因此无法按照输入的顺序输出所有元素。我们可以使用循环遍历集合中的每个元素,并依次输出,中间用空格隔开,最后再输出一个换行符。
示例代码:
```python
s = {1, 2, 3, 4, 5} # 示例集合
for x in s:
print(x, end=' ') # 输出元素,末尾不换行,用空格隔开
print() # 输出一个换行符
```
输出结果:
```
1 2 3 4 5
```
C++输入多个字符串,以空格隔开
你可以使用 C++ 的 cin 或 getline 函数来输入多个字符串,以空格隔开。
使用 cin 函数:
```cpp
#include <iostream>
using namespace std;
int main() {
string s1, s2, s3;
cin >> s1 >> s2 >> s3;
cout << s1 << ", " << s2 << ", " << s3 << endl;
return 0;
}
```
使用 getline 函数:
```cpp
#include <iostream>
using namespace std;
int main() {
string line;
getline(cin, line);
cout << line << endl;
return 0;
}
```
如果你要输入多个字符串,可以使用循环来不断调用 getline 函数。例如:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> words;
string line;
getline(cin, line);
string word;
for (char c : line) {
if (c == ' ') {
words.push_back(word);
word = "";
} else {
word += c;
}
}
words.push_back(word);
for (string w : words) {
cout << w << endl;
}
return 0;
}
```
这个程序会将输入的一行字符串按空格分割成多个单词,并存储到一个 vector 中。