gpt4 book ai didi

c - 我在 "Uva tex quotes"中的答案遇到问题(间距问题)

转载 作者:行者123 更新时间:2023-11-30 19:42:42 27 4
gpt4 key购买 nike

我正在尝试解决 UVAa Online Judge Problem 272 — TeX Quotes .

Input will consist of several lines of text containing an even number of double-quote (") characters. Input is ended with an end-of-file character. The text must be output exactly as it was input except that:

  • the first " in each pair is replaced by two ` characters: `` and
  • the second " in each pair is replaced by two ' characters: ''.

我不知道为什么我的代码给出了错误的答案;我认为这是正确的答案。

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main(){
char kalimat[100000];
int i;
int max;
bool flag=true;
while (scanf("%c",&kalimat)!=EOF){
max=strlen(kalimat);
for (i=0;i<=max;i++){
if (kalimat[i]=='"')
{
if (flag==true){
printf("``");
flag=false;
} else {
printf("''");
flag=true;
}
} else {
printf("%c",kalimat[i]);
}
}
}
return(0);
}

最佳答案

请注意,scanf("%c",&kalimat) 一次仅读取 1(一个)字符。所以 strlen(kalimat) 将始终为 1。不是实际问题,只是奇怪(例如,您可以声明 char kalimat,而不是 char 数组,并且不使用索引或 for 循环)。

但是,您的 for 循环从 0 到 max 包含在内,因此 kalimat 将被索引越界,并导致未定义的行为。也许你的问题就在那里。

事实上,由于 kalimat 是单个字符,因此它不会有终止 '\0' 字符,因此不是有效的 C 字符串。因此 strlen 永远无法计算出正确的长度(即 1)。

试试这个:

char kalimat;
...
while (scanf("%c", kalimat) != EOF) {
if (kalimat == '"') {
if (flag){
printf("``");
flag = false;
} else {
printf("''");
flag = true;
}
} else {
printf("%c", kalimat);
}
}
}

关于c - 我在 "Uva tex quotes"中的答案遇到问题(间距问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31063471/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com