arrays - 在 C 中将 2D Char 数组设置为 Null,但仍然获取 Char 值?
问题描述
本质上,我试图在 C 中创建一个方法,该方法以 char 数组的形式从用户输入一个句子,并在其单独的行上返回每个单词以及句子中的单词总数。例如,如果用户输入“Hi My Name is Fred”。然后,输出应该是单独一行的每个单词,后跟“Total Number of words: 5”。编码似乎很简单,除了一个我根本无法理解的细节。当总字数不是 5(最大值)时,即使我已经将默认值设置为 '\0',我也会得到一堆随机垃圾字符。这是代码:
int splitAndPrintWords(char s[NUM_STRINGS*STRING_LENGTH]) //NUMSTRINGS is 5 while STRING_LENGTH is 50.
{
char str[NUM_STRINGS][STRING_LENGTH]; //An array for storing the sentence word by word
//The first word would be in str[0], the second in str[1], etc.
int count = 0;
for(int k = 0; k < NUM_STRINGS; k++) // Here I loop through the 2D array of chars to set
{ // them all to '\0' values, so they aren't printed.
for(int p = 0; p < STRING_LENGTH; p++)
{
str[k][p] = '\0';
}
}
int k = 0;
int p = 0;
for(int i = 0; i < NUM_STRINGS*STRING_LENGTH; i++) //this loop is for putting each word from the
{ //sentence into the new 2d array.
if(s[i] != ' ') //I use ' ' as the delimiter between words.
{
str[k][p] = s[i];
p++;
}
else
{
k++;
p = 0;
}
}
count = k+1;
for(int i = 0; i < NUM_STRINGS; i++) //lastly I print each word on it's own line, as intended
{
printf("%s\n", str[i]);
}
return count; //returns count so the main method can print how many
} // words are in the sentence.
输出结果如下:
输入单词(最多 5 个):为什么为什么
ùw%Γd±■ t■a
字数= 1
另一个例子是
输入单词(最多 5 个): 这是三 这是三
t■a
字数= 3
我如何摆脱垃圾字符?
解决方案
当您到达s
. 否则,您会将终止符之后的垃圾字符复制到str
.
for(int i = 0; i < NUM_STRINGS*STRING_LENGTH && s[i] != '\0'; i++) //this loop is for putting each word from the
{ //sentence into the new 2d array.
if(s[i] != ' ') //I use ' ' as the delimiter between words.
{
str[k][p] = s[i];
p++;
}
else
{
k++;
p = 0;
}
}
推荐阅读
- td-agent - 在 td-agent 中重新路由到未标记的匹配指令
- r - 数据框的搜索列,每个 i 在同一数据框的另一列中 - R
- python - 使用 Pandas 和 Numpy 通过 ID 索引查找比率的计算时间昂贵
- python - 从csv解析时如何为matplotlib图赋予不同的标题?
- c - 单个字符的scanf()函数不起作用
- minikube - 是否可以为 minikube 使用不同的 VM 映像
- android - Flutter 发布的应用程序不支持 android 版本 10 中的 http ( 不是 https ) 请求
- jasper-reports - Jasper 报告错误从 Bean 检索字段值
- python-3.x - 使用嵌套的索引列表查找列表中的值?
- nlp - 使用对话流模拟时间