如何读取字符串并将其存储到多个变量中
How to read a string of characters and store into multiple variables?
如果我提示用户在一行中输入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::array
,std::vector
,std::list
);
相关文章:
- 存储变量的更有效方法是什么?
- 使用 system() 不存储变量C++?
- 在递归DP中,通过存储变量来分解递归调用:效率低下
- 使用 LDAP 存储C++变量
- 在满足特定条件时运行迭代C++以存储变量
- 使用getline解析和存储变量
- 如何存储变量的地址并使用指针打印值
- C++ / Objective-C++ - 如何在 NSDictionary 中存储C++变量?
- 如何从文件中读取并存储变量
- 指针是否延长了自动存储变量的生存期
- 如何在 INI、CFG 或 XML 文件中存储C++变量
- 如何在 c++ 中的字符串数组中存储变量
- 如何在特定偏移量处存储变量
- 如何存储变量的前一个值并更新它以进行比较
- 存储变量的有效方法是什么?(自制虚拟机)
- 在C++中存储变量
- 在c++中按值调用时,存储变量的副本
- 为什么lambda只捕获自动存储变量
- 如何在寄存器中存储c++变量
- Getline()结合cin.ignore()不存储变量?(错误)