如何将data [i] .int转换为vairable

因此,我是C ++的新手,目前正在使用字符串。并且我想输入一些金额并将它们彼此进行比较,但是由于我将它们以数组的数据类型进行存储,因此它不允许我进行替换,而且我也不明白为什么

for (int i=0;i<N;i++)
{
    cout << "Name"<< endl;
    cin >> data[i].name;
    cin >> data[i].all;
    cin >> data[i].con;
}

exceed = data[i].con-data[i].all;
while (exceed > maxvalue){
maxindex = -1;
maxvalue = exceed;

if (maxvalue > 0){
    cout << data[i].name;
}
smily_lydia 回答:如何将data [i] .int转换为vairable

不知道您为data成员使用的是什么类型,结构或类,或者遇到什么错误,很难告诉您到底发生了什么。您还在for循环之外引用i,所以可能是您遇到的问题。

我重新创建了一个简短的程序,该程序似乎可以使用简单的结构来完成您的目标。由于该结构将conall定义为int类型,因此它们将在输入时进行转换,并且i不再在for循环之外被引用。

#include <iostream>
#include <string>

struct dataType {
    std::string name;
    int all;
    int con;
};

int main() {
    int N = 2;
    int maxValue = 3;
    dataType data[N];

    for (int i = 0; i < N; ++i) {
        std::cout << "Name" << std::endl;
        std::cin >> data[i].name;
        std::cin >> data[i].all;
        std::cin >> data[i].con;

        int exceed = data[i].con - data[i].all;
        if (exceed > maxValue) {
            std::cout << data[i].name << std::endl;
        }
    }
}

如果您使用的结构是conall是字符串,则std :: string stoi中有一种可以将字符串类型转换为int的方法。下面是一个简短的示例。

int x;
std::string test = "4";
x = std::stoi(test);
std::cout << x << std::endl;

请注意,stoi中的无效参数会引发异常,但是作为初学者,您可能尚未了解异常处理(但是一旦掌握了所有知识,就应该知道)。

希望有帮助,加油。

本文链接:https://www.f2er.com/3164793.html

大家都在问