【发布时间】:2018-11-29 22:45:39
【问题描述】:
基本上我有一个由多个单词组成的字符串,如下所示:"Hello world test"。
如果我尝试用这样的结构打印它
printf("%s", string);
或者像这样
for (int i = 0; i < strlen(string); ++i) {
printf("%c", string[i];
}
我总是得到这个作为输出:Hello world,我得到的 strlen 也是 11 而不是 16。
如果我尝试使用以前计算字符串中单个字符的 int 计数器打印出完全相同的字符串
for (int i = 0; i < counter; ++i) {
printf("%c", string[i];
}
我实际上得到了正确的输出Hello world test,这导致人们相信字符串中的元素已正确分配,但由于某种原因 %s 和 strlen 只是忽略了最后一个空格之后的元素。
为什么会这样?到底是怎么回事?我该如何解决这个问题?
编辑:
请求的实际代码:
#include <stdio.h>
#include <string.h>
typedef int BOOL;
#define TRUE 1
#define FALSE 0
int main() {
char sentence[64] = " ", reversal[64] = " ", reversal_copy[64] = " ";
int index = 0, counter = 0;
BOOL reset = TRUE, last_cycle = FALSE;
printf("Enter a sentence: ");
for (int i = 0; sentence[strlen(sentence) - 1] != '\n'; i++) {
scanf("%c", &sentence[i]);
}
/* Copies the input in a string reversing it */
for (int h = strlen(sentence) - 2, k = 0; h >= 0; h--, k++) {
reversal[k] = sentence[h];
}
/* Detects the first character of a word and the last character of the same word before a space,
switching the first char with the last, the second with the pre-last and so on*/
for (int i = 0; i < strlen(reversal); i++) {
if (reset == TRUE) {
index = i;
reset = FALSE;
}
if (i == strlen(reversal) - 1) {
last_cycle = TRUE;
counter++;
}
if (reversal[i] != ' ') {
counter++;
if (last_cycle == TRUE) {
goto reversing;
}
}
else {
reversing:
for (int h = index, z = counter; h < counter; h++, z--) {
reversal_copy[h] = reversal[z - 1];
reversal_copy[z - 1] = reversal[h];
}
if (last_cycle == FALSE) {
reversal_copy[i] = ' ';
}
reset = TRUE;
counter++;
}
}
printf("%lu ", strlen(reversal_copy));
for (int i = 0; i < counter; i++) {
printf("%c", reversal_copy[i]);
}
printf("%s\n\n", reversal_copy);
return 0;
}
【问题讨论】:
-
值
"Hello world test"如何进入string? minimal reproducible example? -
typedef int BOOL;~>#include <stdbool.h>看在上帝的份上。该程序应该做什么(我懒得从代码中弄清楚)?size_t的正确格式说明符strlen()的结果是"%zu"btw。 -
for (int i = 0; sentence[strlen(sentence) - 1] != '\n'; i++) {很奇怪。您应该在分配后在循环内测试sentence[i]。 -
如果您不相信,那么将您的测试 printf(%c) 循环更改为 printf(%x) 循环。你会在那里看到一个 0 (而不是 20 )
-
旁注:
strlen具有非零执行成本,因此请尽量避免在for循环条件子句中使用它。更好:int revlen = strlen(reverse); for (int i = 0; i < revlen; i++) {并同样在该循环中替换它。否则,如果您的长度为 N,您将对字符串中的字符进行N*N扫描。
标签: c