编译器认为 int 是一个字符串.发生了什么事情
Compiler thinks an int is a string. What is happening?
我正在尝试使用此选择排序算法对数组的内容进行排序。但是,我正在使用的编译器(代码块(给了我一个错误,指出"无法在赋值|中将'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;
}
}
错误消息以清晰的方式描述您的代码。
string wordarray [1024]; // strings
/**/
int minvalue; // int
/**/
minvalue = wordarray[startscan]; // attempt to assign a string to an int
你将不得不重新考虑这条线应该做什么。
string wordarray [1024];
是一个字符串数组。从字符串数组中获取元素会给你一个字符串:
auto word = wordarray[someInt]; //word is a string
在C++没有从std::string
到int
的转换。