首页 > 解决方案 > 将 userInput(string) 转换为 UserInput(int) mid for 循环

问题描述

我正在开发一个与数组有关的程序。我决定用户提供的输入是一个字符串,以便稍后在确定它是一个整数后转换为一个整数。这样程序在输入单词/字母时就不会出错。我遇到的问题是从字符串到整数的转换。我想更改它,因为稍后在程序中我将在数组中搜索给定值并显示它及其在数组中的位置。这是我到目前为止的代码:

#include <stdio.h>
#include <iostream>
using namespace std;


//check if number or string
bool check_number(string str) {
   for (int i = 0; i < str.length(); i++)
   if (isdigit(str[i]) == false)
      return false;
      return true;
}
int main()
{
    const int size = 9 ;
    int x, UserInput[size], findMe;
    string userInput[size];
    cout << "Enter "<< size <<" numbers: ";

for (int x =0; x < size; x++)
    {
        cin >> userInput[x];
            if (check_number(userInput[x]))
                {//the string is an int
                }
             else
                {//the string is not an int
                    cout<<userInput[x]<< " is a string." << "Please enter a number: ";
                cin >> userInput[x];}
    }
int i;
for (int i =0; i < size; i++)
    {
          int UserInput[x] = std::stoi(userInput[x]); // error occurs here
    }
for (int x= 0; x< size; x++)
    {
        if (UserInput = findMe)
        {
         cout <<"The number "<< UserInput[x] << "was found at " << x << "\n";
        }
        else
        {
            //want code to continue if the number the user is looking for isn't what is found
        }
        
    }
return 0;
}

在这里和那里发表评论以布局我想要代码做什么等等。我感谢您提供的任何帮助,谢谢。

标签: c++arraysstringinteger

解决方案


这段代码:

int UserInput[x] = std::stoi(userInput[x]);

声明一个intsize 的数组x,您要为其分配一个int(的结果std::stoi),这显然是行不通的。

您需要将 分配给int现有数组的特定索引,如下所示:

UserInput[x] = std::stoi(userInput[x]);

考虑到这个if (UserInput = findMe)实际应该是的比较if (UserInput == findMe),您似乎想要声明一个int存储std::stoi. 在这种情况下,您应该使用与数组不同的名称,并编写如下内容:

int SingleUserInput = std::stoi(userInput[x]);

此外,请一致地缩进您的代码,并在打开所有警告的情况下进行编译。您的代码将更易于阅读,并且编译器会指出您的代码的其他问题。请不要使用using namespace std;,这是一个坏习惯。


推荐阅读