【发布时间】:2018-12-12 02:09:15
【问题描述】:
想法: 我正在尝试创建一个在 .txt 文件中搜索用户输入字词的程序。没有给出单词的大小。我想找到一种动态存储用户单词的方法,以便能够将其与文件中的其他单词进行比较。
整个程序很大,所以我只附上与我的问题相关的部分。
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>
void vectorfill(vector<char>& newword) //filling char vector
{
char input;
scanf_s("%c", &input);
while (input != -1)
{
newword.push_back(input);
scanf_s("%c", &input);
}
}
int main (void)
{
vector<char> word;
printf("Enter a word: (-1 to finish)");
vectorfill(word);
}
问题:
1) 在这种情况下,char 向量是一个最好的主意吗?
2)(如果我们擅长 char 向量)如何让编译器理解用户写完他们的单词?我们可以要求他把(-1)放在最后吗?有没有更好的方法来标记输入的结束?
【问题讨论】:
-
和
while (input != -1),这并不像你认为的那样。 :-) -
打开你的 C++ 书籍到解释如何使用
std::string和std::getline()的章节,然后阅读它。这是 C++。使用像scanf和朋友这样笨拙的 C 库函数没有必要跳过箍,当像std::getline() 这样更复杂和方便的 C++ 库函数会做得更好时。 -
您必须决定是编写 C 还是 C++ - 这些是具有不同解决方案的不同语言。在 C++ 中,您可以使用
std::string存储单词并使用std::cin从控制台标准输入读取一行。 -
使用字符串存储用户的话。将文件分成字符串单词向量,检查向量是否包含用户的单词。