如何读取字符串并将其存储到多个变量中

How to read a string of characters and store into multiple variables?

本文关键字:存储 变量 串并 何读取 读取 字符串 字符      更新时间:2023-10-16

如果我提示用户在一行中输入6个数字,例如:

3 4 5 6 7 8

如何将第一个数字存储在字符串中,将第一个数字存储到变量Num1,第二个数字中,将Num2、3数字存储到变量Num3等中?即,我需要提示用户输入包含6个不同数字的单行,然后将这6个数字分为6个不同的变量。

这是我的代码:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string num;
    cout << "Enter one line containing 6 integers" << endl; 
    getline(cin, num)
    return 0;
}

不确定string是否是正确使用的类型。

此方法使所有6个数字都存储在num中,而不是将6个数字拆分为单独的变量。

您可以喜欢:

cin>>num1>>num2>>num3>>num4>>num5>>num6;

c 在空间字符上打破字符串。

使用'cin'代替" getline"。

在C中您可以使用strtok的拆分字符串。

请参阅本教程:http://www.c-howto.de/tutorial-strings-zeichenetten-stringfunktionen-zerteilen-strtok.html

对于C ,我们已经有一个问题可以解决您的需求:在C 中拆分字符串?

希望这对您有帮助。

您可以做您在问的事情

std::string line;
std::getline(std::cin, line);
std::istringstream iss(line);
iss >> num1 >> num2 >> num3 >> num4 >> num5 >> num6;

但是,我强烈建议您查看一个容器(例如std::arraystd::vectorstd::list);