【发布时间】: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