我正在为考试学习C++,有一件事是困扰我。
我有一个包含25个单词的文件(我们称它为“new.txt”)和一个包含1000个单词的文件(“words.txt”)。
我必须检查new.txt中的单词出现在words.txt中的次数。然后,我必须检查new.txt单词的“镜像”在words.txt中出现了多少次(镜像意味着单词从右到左=> car = rac ..)
我的想法是制作三个数组:newword [25],words [1000],mirror [25],然后从那里开始。
我知道如何使用“char”数据类型执行此操作。但我想尝试使用“字符串”类型。
这是代码:
string mirrors(string word) //function that writes the word from the back
{
int dl=word.length();
string mir;
for (int q=0;q<dl;q++)
{
mir[q]=word[dl-q-1]; //first letter of a new word is a last letter of the original word
}
return mir;
}
int main()
{
ifstream in1 ("words.txt");
ifstream in2 ("new.txt");
string words[1000], newword[25], mirror[25]; //creating arrays
for (int x=0;x<1000;x++) //filling the array with words from words.txt
{
in1>>words[x];
}
for (int y=0;y<25;y++) //filling the array with words from new.txt
{
in2>>newword[y];
}
in1.close();
in2.close();
for (int z=0;z<25;z++)
{
mirror[z]=mirrors(newword[z]);
}
out.close();
return 0;
}
这是问题所在...
当我更改字母顺序时,“mirror”中的字符串不会使用普通cout
所以我的问题是...是否存在一些字符串数据类型,使得在创建一个字母一个字母一个字母的字母后无法使用一个命令进行打印,还是有什么我不知道的东西?
因为单词在那里,所以在此数组中创建了单词。但是cout <
如果问题不清楚,我们很抱歉,但这是我第一次在这里发布...
最佳答案
string mirrors(string word) {
int dl = word.length();
string mir; // here you declare your string, but is's an empty string.
for (int q = 0; q < dl; q++) {
// by calling mir[q] you are referencing to the [0, 1 ... dl-1] char of empty string (so it's size = 0) so it's undefined bhv/error.
// mir[q]=word[dl-q-1]; //first letter of a new word is a last letter of the original word
mir = mir + word[dl - q - 1]; // you rather wanted to do smth like this
}
return mir;
}
关于c++ - C++:在字符串数据类型中创建单词 “letter after letter”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48308235/