这是我在堆栈溢出中的第一个问题,所以如果有一些错误对此感到抱歉。我正在尝试填充 2d 字符数组,然后访问每个字母。我编译了我的代码,没有错误,但是当我尝试运行它时它不起作用。这是我的代码。
#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
int main() {
char ch[] = "Welcome text in a separate line.";
char strWords[5][7];
int counter = 0;
int a = 0;
for (int i = 0; i < sizeof(ch); i++) {
if (ch[i] == ' ') {
strWords[counter][a] = '\0';
counter++;
a = 0;
}
else
{
strWords[counter][a] += ch[i];
a++;
}
}
for (int i = 0; i <= 5; i++) {
for (int a = 0; a <= 7; a++) {
cout << strWords[i][a] << " ";
}
}
return 0;
}
回答1
您的代码有一些问题
int main() {
char ch[] = "Welcome text in a separate line.";
// char strWords[5][7]; <<<=== i would change to be larger that you need, just in case
char strWords[20][20];
int counter = 0;
int a = 0;
for (int i = 0; i < strlen(ch); i++) { // sizeof is wrong, you need strlen
if (ch[i] == ' ') {
strWords[counter][a] = '\0';
counter++;
a = 0;
}
else
{
//strWords[counter][a] += ch[i];
strWords[counter][a] = ch[i]; // you do not need to try to concatenate, you are already walking down the buffer with 'a'
a++;
}
}
for (int i = 0; i < counter; i++) { // use 'counter' as it has the number of lines
// since you 0 terminated the string you do not need to walk character by character
cout << strWords[i] << " ";
}
return 0;
}
您也没有检测和终止最后一个单词(因为它后面没有空格)。我会把它留给你。我显示的代码不打印单词“line”。
您确实应该进行测试以确保您不会超出单词的长度或数量。
另外,您最好使用 std::string
和 std::vector
注意 - 如果为了实验,您确实想逐个字符地遍历以输出字符串,您应该查找终止的 '0' 字符并退出内部循环