使用getline()时将字符串转换为数字 我已经拿起一本关于C++的书,基本上是在刚开始的时候。对于我在书中必须解决的一些问题,我使用了以下方式的输入流-->

使用getline()时将字符串转换为数字 我已经拿起一本关于C++的书,基本上是在刚开始的时候。对于我在书中必须解决的一些问题,我使用了以下方式的输入流-->,c++,C++,但是后来我做了一些研究,发现cin会导致很多问题,因此我发现了头文件sstream中的函数getline() 我只是在试图理解下面代码中发生的事情时遇到了一些麻烦。我没有看到任何使用提取运算符(>>)将数值存储在中的内容。这(我的问题)在我留下的评论中得到了进一步的解释 #include <iostream> #include <string> #include <sstream> using namespace std; // Program that al

但是后来我做了一些研究,发现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;
//允许用户更改存储在数组元素中的值的程序
int main()
{
字符串输入=”;
常量int数组_长度=5;
int MyNumbers[ARRAY_LENGTH]={0};
//混乱从哪里开始
cout>nElementIndex)//在前面的任何一行中,它实际上都没有从输入中提取任何内容并将其存储在nElementIndex中吗?
break;//停止循环
coutstringstream myStream(input):创建一个新的流,该流使用input中的字符串作为“input stream”

if(myStream>>nElementIndex){…:从使用上述行创建的stringstream中提取数字到nElementIndex并执行…,因为表达式返回myStream,myStream应为非零

在if语句中使用提取作为条件可能会使您感到困惑。上述内容应等同于:

myStream>>nElementIndex; // extract nElement Index from myStream
if(myStream)
{
   ....
}
你可能想要的是

myStream>>nElementIndex; // extract nElement Index from myStream
if(nElementIndex)
{
   ....
}

怎么样?我对这种方法的作用感到困惑,但请注意,它并不比使用
cin>>某些变量更好。您所做的只是使代码更复杂,效率更低。对于您的实际问题,请参阅:@JoachimPileborg不知道那是什么,刚开始学习该语言,我想我会在这之后再研究它。我不想仅仅因为程序一结束{expletive}控制台就消失了,MSVC就把事情变得不必要的复杂化。Nadim:
#include
,和
cin.ignore(std::numeric_limits::max(),'\n');
来清除
cin
(或者任何输入流,真的)。
myStream>>nElementIndex; // extract nElement Index from myStream
if(nElementIndex)
{
   ....
}