我拿起了一本关于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;
}
std::stoi
怎么样? - Some programmer dudecin >> some_variable
更好。你所做的只是让代码变得更加复杂和低效。 - NathanOliver#include <limits>
和cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
来清除未读取的输入(无论是cin
还是任何输入流)。 - DevSolar