【问题标题】:Convert userInput (string) to UserInput(int) mid for loop将用户输入(字符串)转换为用户输入(int)中间for循环
【发布时间】:2020-12-29 10:32:18
【问题描述】:

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

#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;
}

在这里和那里制作 cmets 来布局我想要代码做什么等等。我很感谢您能提供的任何帮助,谢谢。

【问题讨论】:

  • if (UserInput = findMe) 总是 计算结果为 true。使用if (UserInput == findMe) 检查是否相等
  • check_number 中返回的格式让我很焦虑
  • 另外UserInput 是一个数组。为什么要将它与int 进行比较?
  • 整个程序可以用不到 15 行 "real" c++ 代码编写。看起来你不必要地把事情复杂化了。
  • 为什么缩进这么乱?你只是让自己的生活变得艰难。见:format.krzaq.cc

标签: c++ arrays string integer


【解决方案1】:

这段代码:

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

声明一个大小为xint 数组,您将为其分配一个intstd::stoi 的结果),这显然不起作用。

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

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

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

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

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

【讨论】:

    【解决方案2】:

    我不明白为什么你甚至需要使用另一个循环将字符串值转换为 int。 stdio.h 头文件确实提供了预装的功能,让您的工作更轻松...

    for (int x =0; x < size; x++)
        {  
            getline(cin,userInput1[x]);
           UserInput[x]=stoi(userInput1[x]);
        }
    

    stoi()函数将输入的字符串转换为int,输入字符串就可以动态调用,让你工作更轻松,降低时间复杂度

    【讨论】:

      猜你喜欢
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-06
      相关资源
      最近更新 更多