0

我已经为这个问题编写了 C++ 代码。问题基本上是用 替换开头"``结尾。"''

这很容易,但我得到了错误的答案。有人可以帮我找出我的代码的问题吗?

样本输入:

"To be or not to be," quoth the Bard, "that
is the question".
The programming contestant replied: "I must disagree.
To `C' or not to `C', that is The Question!"

样本输出:

``To be or not to be,'' quoth the Bard, ``that
is the question''.
The programming contestant replied: ``I must disagree.
To `C' or not to `C', that is The Question!''

代码:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main(){
    string inputString;

    while (getline(cin, inputString)){
        int nDoubleQuotes = 0;

        for (int i = 0 ; i < (int)inputString.length(); ++i){
            if (inputString[i] == '"'){
                ++nDoubleQuotes;

                nDoubleQuotes = nDoubleQuotes%2;

                if (nDoubleQuotes == 1)
                    cout << "``";
                else
                    cout << "''";
            }
            else
                cout << inputString[i];
        }

        cout << '\n';
        inputString.clear();
    }
    return 0;
}
4

2 回答 2

2

不幸的是,您的代码甚至没有通过示例测试用例!无论如何,只需将这一行放在int nDoubleQuotes = 0;循环之外while( getline( cin , inputString ) ),您需要这样做的原因是,在输入文件中,引号(“)可以在一行开始,可以在任何其他下一行结束,作为示例测试用例在问题陈述中显示:

The programming contestant replied: "I must disagree. #quote start on this line
To `C' or not to `C', that is The Question!" #quote ends on this

如果您在每一行上初始化引号计数器变量,那么您假设引号标记开始和结束在同一行,这是错误的。

于 2013-07-24T05:43:52.887 回答
1

您可以一次读取一个字符来解决这个问题。您需要跟踪您是否在报价范围内,以便打印正确的替换"

#include <iostream>

int main()
{
    bool inquote = false;
    char ch;
    while (std::cin.get(ch)) {
        if (ch == '"') {
            std::cout << (inquote ? "''" : "``");
            inquote = !inquote;
        } else {
            std::cout << ch;
        }
    }
}
于 2013-07-24T17:08:03.027 回答