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

标签 c quotes tex

我正在尝试解决 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/

相关文章:

javascript - 当从 javascript 调用字符串时,Latex 不渲染?

latex - 新命令 for\end{tabular}\\?绕过语法和转义

c - 另一个条件运算符嵌套问题

c - 基本 C 程序无输出

c - 这个 char* 赋值发生了什么? (混合类型的逗号运算符)

mysql - 如何将mysql_real_escape_string()的结果插入到oracle数据库中?

c# - 需要 RegEx 或其他方式来分隔包含转义引号的引用标记

node.js - 从纯文本到 TEX - Javascript

将温度从摄氏温度转换为华氏温度

C++数组传递给函数被切断