【问题标题】:How to store a single word in a vector ? (c++)如何将单个单词存储在向量中? (c++)
【发布时间】: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::stringstd::getline() 的章节,然后阅读它。这是 C++。使用像 scanf 和朋友这样笨拙的 C 库函数没有必要跳过箍,当像 std::getline() 这样更复杂和方便的 C++ 库函数会做得更好时。
  • 您必须决定是编写 C 还是 C++ - 这些是具有不同解决方案的不同语言。在 C++ 中,您可以使用 std::string 存储单词并使用 std::cin 从控制台标准输入读取一行。
  • 使用字符串存储用户的话。将文件分成字符串单词向量,检查向量是否包含用户的单词。

标签: c++ string vector char


【解决方案1】:

1> 不。使用std::string

2> 是的。使用空格。

例子:

#include <iostream> 
#include <string>

int main ()
{
    std::string word; 
    std::cout << "Enter a word" << std::endl;
    std::cin >> word;
    // do something with word. For example, 
    std::cout << "You entered" << word << '\n';
}

只要用户输入至少一个数字、字母或其他非whitespace character 后跟空格字符,就会在word 中捕获一个单词。如果你有特殊要求,比如这个词只能包含字母(没有数字、铃铛、ASCII 艺术字符等),一个带有isalpha 的简单循环可以用几行代码来解决这个问题,但不会少到std::find_ifisalpha

【讨论】:

  • 非常感谢,但是当我写“something(spacebar)”时,我的程序没有做任何事情。然后它在点击进入时关闭。怎么了?
  • 这个例子只展示了如何获取数据。它对它没有任何作用。会更新。
【解决方案2】:

如果搜索内容是txt文件。使用std::vector&lt;std::string&gt; 可能会更好。您可以使用 split char 来拆分单词。

如果内容来自用户的键盘输入。您还可以使用std::string 存储输入的每个单词,并将其存储在std::vector&lt;std::string&gt; 中。就像这样:

std::string s;
std::vector<std::string> vec;
std::cout << "Please enter somestring" << std::endl;
while (cin >> s)
{
    vec.push_back(s);
    cout << "You have entered : " << s << endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多