首页 文章

编译器认为int是一个字符串 . 怎么了?

提问于
浏览
-9

我试图使用这种选择排序算法来排序数组的内容 . 但是我正在使用的编译器(codeblocks)给出了一个错误说明"cannot convert 'std::string ' to 'int' in assignment|."这是参考行读取 minvalue = wordarray[startscan]; minvalue和startscan都是int,而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;
        }

    }

2 回答

  • 4

    string wordarray [1024]; 是一个字符串数组 . 从字符串数组中获取元素会为您提供一个字符串:

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

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

  • 2

    错误消息以清晰的方式描述您的代码 .

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

    你将不得不重新考虑该线应该做什么 .

相关问题