如何将字符串添加到字符串数组中

How do you add strings to an array of strings

本文关键字:字符串 数组 添加      更新时间:2023-10-16

我创建了一个程序,将英语单词转换为pig拉丁语(我的课程的一部分)。目前,它只转换一个词:"你好"->"你好"。

出于我自己的好奇心,我想有可能阅读多个用空格分隔的单词,然后对每个单词进行相应的转换。

更严格地说,使用substr在两个连续空间之间抓取一个单词。输入将被CCD_ 2分解为分离的单词。一段时间内的每个单词都将由我的make_pig_latin解析器解析,并将在该string array中替换她对应的单词。

例如:输入"你好,黄人"将导致输出"elloyay elloway ellowayy"

有人能告诉我,我完成这项任务的编码是否在正确的轨道上吗。我在运行时不断崩溃,我认为这是由于没有正确创建字符串数组造成的。但我不完全确定。

如有任何帮助,我们将不胜感激。

int main()
{
    string word;
    string word_List[] = { word };
    cout << "Enter your story (Please include spaces between each word): ";
    getline(cin, word);
    char c = word[0];
    int i = 0;
    int j = 0;
    int k = i;
    int l = 0;
    while (i < (word.length() - 1))
    {
        if (word[i] = 'n')
        {
            string new_Word = word.substr(j, k);
            string test_Pig = make_Pig_Latin(new_Word);
            word_List[l] = test_Pig;
            l == l + 1;
            j == i + 1;
            i == k + 1;
        }
        if (word[i] = '.')
        {
            i = word.length() + 1;
        }
    }
    cout << "The Story In Pig Latin Is " << word_List << endl;
    cin.ignore();
    cin.get();
    return EXIT_SUCCESS;
}

用户要添加的额外信息:完整的错误行、使用的编译器+版本、使用的操作系统。

if (word[i] = 'n')将把word[i]设置为'n'。你可能是想测试if(word[i] == 'n')...

然而,您一次只得到一行输入,中间没有新行。

您可以通过测试空白if(word[i] == ' ')... 来打断文本

碰巧有一种更简单的方法。使用std::stringstream提取单词。使用std::vector制作字符串数组(或者向量)。示例:

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int main()
{
    std::string sentence = "How do you add strings to an array of strings";
    std::vector<std::string> vs;
    std::stringstream iss(sentence);
    std::string word;
    while (std::getline(iss, word, ' '))
        vs.push_back(word);
    for (auto wrd : vs)
        cout << wrd << "n";
    return 0;
}