使用getline()时将字符串转换为数字
Converting string to number when using getline()
我读了一本关于C++的书,我基本上处于它的最开始(刚刚开始)。对于我在书中必须解决的一些问题,我使用输入流cin的方式如下-->
cin >> insterVariableNameHere;
但后来我做了一些研究,发现cin会引起很多问题,所以我发现了头文件sstream中的函数getline()。
我只是在试图理解以下代码中发生的事情时遇到了一些麻烦。我没有看到任何使用提取运算符(>>)来存储数值的东西。这(我的问题)在我留下的评论中得到了进一步解释。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
// Program that allows a user to change the value stored in an element in an array
int main()
{
string input = "";
const int ARRAY_LENGTH = 5;
int MyNumbers[ARRAY_LENGTH] = { 0 };
// WHERE THE CONFUSION STARTS
cout << "Enter index of the element to be changed: ";
int nElementIndex = 0;
while (true) {
getline(cin, input); // Okay so here its extracting data from the input stream cin and storing it in input
stringstream myStream(input); // I have no idea whats happening here, probably where it converts string to number
if (myStream >> nElementIndex) // In no preceding line does it actually extract anything from input and store it in nElementIndex ?
break; // Stops the loop
cout << "Invalid number, try again" << endl;
}
// WHERE THE CONFUSION ENDS
cout << "Enter new value for element " << nElementIndex + 1 << " at index " << nElementIndex << ":";
cin >> MyNumbers[nElementIndex];
cout << "nThe new value for element " << nElementIndex + 1 << " is " << MyNumbers[nElementIndex] << "n";
cin.get();
return 0;
}
字符串流myStream(input):创建一个新的流,可以说,该流使用输入中的字符串作为"输入流"。
if(myStream>>nElementIndex){…):将使用上面一行创建的字符串流中的数字提取到nElementIndex中并执行…,因为表达式返回的myStream应为非零。
如果在if语句中使用提取作为条件,您可能会感到困惑。以上应等同于:
myStream>>nElementIndex; // extract nElement Index from myStream
if(myStream)
{
....
}
你可能想要的是
myStream>>nElementIndex; // extract nElement Index from myStream
if(nElementIndex)
{
....
}
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组