c++ - 将 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;
}
在这里和那里发表评论以布局我想要代码做什么等等。我感谢您提供的任何帮助,谢谢。
解决方案
这段代码:
int UserInput[x] = std::stoi(userInput[x]);
声明一个int
size 的数组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;
,这是一个坏习惯。
推荐阅读
- python - 使用 brew (homebrew) 在 Mac 上安装后,python 无法导入图形工具
- python - 为什么我遇到 kivy 设计师的“kivy.adapters”问题?
- python - 调用 canvas.draw() 时 Matplotlib imshow 不更新
- java - prepareStatement 为 getPassword 抛出错误
- google-analytics-api - 无法使用 Google Analytics API 加载帐户
- angular - Angular:在其他任何事情之前完全安装服务工作者
- c++ - 如何在 GMock 中使用带有测试夹具的模拟?
- r - R 从 Sparklyr 中的 ALS 实施中提取潜在因素
- ruby-on-rails - 定期 PG::UndefinedTable: 错误: 关系不存在错误
- java - 在 Java 中为接口实例列表实现通用容器