当字符串为"\0"时如何结束 2D 字符数组?

How to end a 2D char array when string is ''?

本文关键字:结束 2D 字符 数组 何结束 字符串      更新时间:2023-10-16

我有一个程序,可以向用户查询存储在2D字符数组中的字符串输入。当输入20个字符串或当用户两次点击回车键时,程序应停止要求输入。

出于某种原因,无论我做什么,程序都会继续显示所有空字符串,即使用户还没有填充它们。我该怎么阻止?

int main()
{
char sentences[20][81] = { '' };
cout << "Enter up to 20 sentences - when done, Press ENTER: ";
input(sentences);
for (int i = 0; i < 20; i++)
{
if (sentences[i] == '' || sentences[i] == "n")
break;
else
{
cout << "nHere is sentence " << i + 1 << ": " << endl << sentences[i] << endl;
menu(sentences[i]);
}
}
cout << "nPress any key to continue...";
_getch();
return 0;
}
void input(char str[20][81])
{
for (int i = 0; i < 20; i++)
{
cin.getline(str[i], 81, 'n');
if (str[i][0] == '')
break;
}
}

没有错误消息,我希望在这里检查

if (sentences[i] == '' || sentences[i] == "n"
break;

应该在遇到空白的c字符串时结束程序,为什么没有发生这种情况?

此处的检查错误:

if (sentences[i] == '' || sentences[i] == "n")

您正在比较sentences[i](char*(和''(char(。sentences[i] == "n"部分完全错误——去掉它。你的支票应该是这样的:

if (sentences[i][0] == '' )

但我真的建议使用std::vector<std::string>,而不是这种多维c风格的字符串构造。您只需使用push_back将字符串添加到向量中,并使用基于范围的循环来遍历向量并打印其结果。你可以用input函数这样做:

void input(std::vector<std::string> &sentences)
{
for (int i = 0; i < 20; i++)
{
std::string s;
std::getline(std::cin, s);
if (s.empty())
break;
sentences.push_back(s);
}
}

然后main的功能是这样的:

int main()
{
std::vector<std::string> sentences;
std::cout << "Enter up to 20 sentences - when done, Press ENTER: " << std::endl;
input(sentences);
for (int i = 0; i < sentences.size(); i++)
std::cout << "Here is sentence " << i + 1 << ": " << std::endl << sentences[i] << std::endl;
std::cout << "Press any key to continue...";
//getch();
return 0;
}

这样,你甚至不需要20句子的硬编码限制,你可以去掉它,改为使用while (true)循环。