如何将字符串添加到字符串数组中
How do you add strings to an array of strings
我创建了一个程序,将英语单词转换为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;
}
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组