我正在为我的考试学习C++,有一件事困扰着我。
我有一个有25个单词的文件(让我们称之为"new.txt")和一个1000个单词的文件("words.txt")。
我必须检查new.txt中一个单词在words.txt中出现了多少次。在此之后,我必须检查new.txt单词的“镜像”在words.txt中出现了多少次(镜像的意思是从右到左的=> car =rac.)
我的想法是制作三个数组: newword25、words1000、mirror25,然后再从那里生成一个数组。
我知道如何使用"char“数据类型来完成此操作。但我想试着用"string“类型来做。
以下是代码:
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;
}
问题是..。当我更改字母顺序时,“镜像”中的字符串不会使用普通cout<打印
所以我的问题是..。有什么字符串数据类型使得在创建一个又一个字母之后无法使用一个命令打印,还是有什么我不知道的东西?
因为单词在那里,所以它是在这个数组中创建的。但cout<
如果问题不清楚,我很抱歉,但这是我第一次在这里发帖.
发布于 2018-01-17 11:23:15
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;
}
发布于 2018-01-17 11:37:31
首先,您尝试访问空std::string
中的符号,这将导致UB。在实践中,所有这些都是不必要的:
std::string mirrors( const std::string &word) //function that writes the word from the back
{
return std::string( word.rbegin(), word.rend() );
}
就够了。至于您的程序,将文件"new.txt“的内容读入内存会好得多,而std::set
或std::unordered_set
则更适合查找。然后创建2个实例std::map<std::string,int>
(或者std::unordered_map
,如果您不关心顺序)并逐个读取文件"word.txt“,相应地计数和更新这些映射:
std::unordered_set<std::string> new_words; // this should be populated from file "new.txt"
std::map<std::string,int> counts, mcounts;
// reading loop of file "words.txt"
std::string word = ...;
counts[ word ] += new_words.count( word );
word = mirrors( word );
mcounts[ word ] += new_words.count( word );
那你就有你所有的数目了。
https://stackoverflow.com/questions/48308235
复制