在C++中的一行中插入多个输入

nxagd54h  于 2023-06-25  发布在  其他
关注(0)|答案(5)|浏览(147)

我尝试在一行中插入多个输入,输入之间使用逗号和空格。到目前为止我一直使用的方法是用空格分隔输入。

  1. int a, b , c ,d
  2. cin >> a >> b >> c >> d ;

使用此方法,输入行如下所示:
但我希望能够输入这样的数据:

  1. 1, 2, 3, 4
uelo1irk

uelo1irk1#

>>的分隔符是不可修改的,但可以将其与ignore组合使用:

  1. std::cin >> a;
  2. std::cin.ignore(1, ',')
  3. // rinse and repeat
xoshrz7s

xoshrz7s2#

你可以这样做:

  1. int main() {
  2. int a,b,c,d;
  3. char comma;
  4. std::cin >> a >> comma >> b >> comma >> c >> comma >> d;
  5. std::cout << a << " " << b << " " << c << " " << d << std::endl;
  6. return 0;
  7. }

输入:

  1. 1, 2, 3, 4

输出:
演示:http://www.ideone.com/tXQZd

3duebb1j

3duebb1j3#

在C / C++中,你只需要这样做:

  1. scanf("%d, %d, %d, %d", &a, &b, &c, &d);

您只需要包含<cstdio>

9ceoxa92

9ceoxa924#

你可以这样做-

  1. for (int i = 0; i < 6; i++)
  2. {
  3. /* code */
  4. for (int j = 0; j < 6; j++)
  5. {
  6. /* code */
  7. cin >> arr[i][j];
  8. cin.ignore(1, ' ');
  9. }
  10. cout << endl;
  11. }

这将采用6*6数组输入作为
-9 -9-9 -9 11 1
0 - 9 0 4 3 2
-9 - 9 - 9 1 2 3
0 0 8 6 6 0
0 0 0 - 2 0 0
0 0 1 2 4 0

展开查看全部
gzszwxb4

gzszwxb45#

你可以这样做,在输入上运行一个循环,并将所有输入放入数组/向量中,然后使用该数组/向量。

  1. #include <iostream>
  2. #include <vector>
  3. int main() {
  4. std::vector<int> numbers;
  5. int num;
  6. // Read inputs until the end of the line
  7. while (std::cin >> num) {
  8. numbers.push_back(num);
  9. // Check for newline character or end of file
  10. if (std::cin.peek() == '\n' || std::cin.peek() == EOF)
  11. break;
  12. }
  13. // Print the numbers
  14. for (int i : numbers) {
  15. std::cout << i << " ";
  16. }
  17. return 0;
  18. }
展开查看全部

相关问题