【问题标题】:Compiler thinks an int is a string. What is happening?编译器认为 int 是一个字符串。怎么了?
【发布时间】:2018-07-04 10:09:28
【问题描述】:

我正在尝试使用此选择排序算法对数组的内容进行排序。但是,我正在使用的编译器(代码块)给了我一个错误,指出“无法在赋值中将 'std::string {aka std::basic_string}' 转换为 'int'|。”这是参考minvalue = wordarray[startscan]; 的行,minvalue 和 startscan 都是整数,而 wordarray 是一个数组。这是我的代码:

    #include <iostream>
#include <fstream>

using namespace std;

string wordarray [1024];
int main()
{
    int wordcount = 0;
    string filename;
    cout << "Please enter the name and location of your file." << endl;
    cin >> filename;
    ifstream testfile;
    testfile.open (filename.c_str());
    for (int i=0; i < 1024; ++i)
    {
        testfile >> wordarray[i];
        cout << wordarray[i] << endl;
    }
    testfile.close();
}
void arraysort (int size)
    {
        int startscan, minindex;
        int minvalue;
        for (startscan = 0; startscan < (size - 1); startscan++)
        {
        minindex = startscan;
        minvalue = wordarray[startscan]; //here
            for (int index = startscan + 1; index < size; index ++)
            {
                if (wordarray[index] < minvalue)
                {
                     minvalue = wordarray[index];
                     minindex = index;
                }
             }
             wordarray[minindex] = wordarray[startscan];
             wordarray[startscan] = minvalue;
        }

    }

【问题讨论】:

  • Code::Blocks 不是编译器。并且错误消息非常字面。而且编译器不会像你想的那样思考。
  • 那么为什么它认为已经声明为int的值是字符串呢?
  • 我说,“而且编译器不会像你想的那样思考。”
  • &gt;&gt; So why is it that it believes that a value that has been declared as an int is a string? 它没有。它只是说您不能将string 分配给int
  • 我认为回答者(包括我在内)和您对情况和所涉及的数据类型有非常不同的看法。这不一定是您的错,并且可能使您无法找到任何有用的答案。我提议在聊天中做一些互动帮助,如果你在网上找到我,最好在几个小时内聊天,否则在这里用“@Yunnosch”写评论以引起我的注意 - 比如说 6 小时内。

标签: c++ arrays sorting


【解决方案1】:

错误消息清楚地描述了您的代码。

string wordarray [1024]; // strings
/**/
int minvalue; // int
/**/
minvalue = wordarray[startscan]; // attempt to assign a string to an int

您将不得不重新考虑该行应该做什么。

【讨论】:

    【解决方案2】:

    string wordarray [1024]; 是一个字符串数组。从字符串数组中获取一个元素会给你一个字符串:

    auto word = wordarray[someInt]; //word is a string
    

    在 C++ 中,没有从 std::stringint 的转换。

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 2011-05-26
      • 2011-05-16
      • 2020-03-08
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 2013-02-27
      相关资源
      最近更新 更多