C++ getline 或 cin 不接受带空格的字符串,我搜索过 Google 但仍然被难住了!

发布于 2024-09-07 23:26:40 字数 3462 浏览 4 评论 0原文

首先感谢所有帮助过我的人,非常感谢!

我试图将带有空格和特殊字符的字符串完整存储到 MessageToAdd 中。

我正在使用 getline (cin,MessageToAdd); 并且我也尝试了 cin >>>消息添加;

我很困惑!当我输入示例输入时

测试

一切都按预期工作。但是如果我要使用

测试测试测试

整个控制台会快速闪烁,直到我按下CtrlC

有人告诉我,我将变量放在顶部的风格已经过时了。请原谅我,因为我仍在自学,这只是习惯的力量。解决这个问题后我会很快改变我的风格:)

void AddMessage() {
    ifstream myReadFile;
    string str;
    string MessageToAdd;
    string myMessages[10];
    int i; // of course my famous i
    static string rowHtmlCloseTags;
    static string rowHtmlOpenTags;
    string replacement;

    myReadFile.open("C:\\Users\\Andrews\\Documents\\Visual Studio 2010\\Projects\\computerclass\\Debug\\outages.htm",ios::in);
    i = 0; //the start of my array
    rowHtmlCloseTags = "</b></td>"; // value that I want to replace with nothing
    rowHtmlOpenTags = "<td><b>";

    if(!myReadFile) // is there any error?
    {
        cout << "Error opening the file! Aborting…\n";
        exit(1);
    }

    if (myReadFile.is_open())
    {
        cout << endl;

        while (!myReadFile.eof())
        {
            getline(myReadFile, str);

            if (str == "<tr>")
            {            
                getline(myReadFile, str); //get the next line cause thats where the <td><b>Outage Message</b></td> is.
                size_t foundIndex = str.find(rowHtmlCloseTags); //does the sought string exist in this this line?
                if (foundIndex != str.npos) //if not no position
                    str.replace(foundIndex, rowHtmlCloseTags.size(), replacement); //replace the string
                else
                    std::cout << "Oops.. didn't find " << rowHtmlCloseTags << std::endl; //else throw a bitch

                foundIndex = str.find(rowHtmlOpenTags); //does the sought string exist in this this line?
                if (foundIndex != str.npos) //if not no position
                    str.replace(foundIndex, rowHtmlOpenTags.size(), replacement); //replace the string
                else
                    std::cout << "Oops.. didn't find " << rowHtmlOpenTags << std::endl; //else throw a bitch

                myMessages[i]=str;
                i++;
            }
        }
    }
    system("cls");
    i=0;
    while (i < 10)
    {
        cout << i << ") " << myMessages[i] << endl;
        i++;
        if (myMessages[i]=="")
        {
            break;
        }
    }
    myReadFile.close();
    cout << endl;
    cout << endl;
    cout << "Enter the message you would like to see on the reader board.\n";
    cout << "Or enter 911 to go back to the main menu: ";
    cin.ignore(1080);
    getline (cin,MessageToAdd);

    if (str == "911") //go back to the main menu
    {
        system("cls");
        mainMenu();
    }
    else //insert the message into a blank spot in the array
    {
        i=0;
        while (i < 10)
        {
            if (myMessages[i].empty())
            {
                myMessages[i]=MessageToAdd;
                break;
            }
            else
            {
                i++;
            }
        }
    }

    //now rebuild the htm file with the new array
    CreateHtmlFile(myMessages);
}

First of all, thanks to everyone who helps me, it is much appreciated!

I am trying to store a string with spaces and special characters intact into MessageToAdd.

I am using getline (cin,MessageToAdd); and I have also tried cin >> MessageToAdd;.

I am so stumped! When I enter the sample input

Test

Everything works as intended. However if I were to use

Test Test Test

The whole console would just blink fast until I pressed CtrlC.

My style of putting variables at the top I've been told is obsolete. Please forgive me as I am still teaching myself and it's simply force of habit. I will be changing my style shortly after I get this solved :)

void AddMessage() {
    ifstream myReadFile;
    string str;
    string MessageToAdd;
    string myMessages[10];
    int i; // of course my famous i
    static string rowHtmlCloseTags;
    static string rowHtmlOpenTags;
    string replacement;

    myReadFile.open("C:\\Users\\Andrews\\Documents\\Visual Studio 2010\\Projects\\computerclass\\Debug\\outages.htm",ios::in);
    i = 0; //the start of my array
    rowHtmlCloseTags = "</b></td>"; // value that I want to replace with nothing
    rowHtmlOpenTags = "<td><b>";

    if(!myReadFile) // is there any error?
    {
        cout << "Error opening the file! Aborting…\n";
        exit(1);
    }

    if (myReadFile.is_open())
    {
        cout << endl;

        while (!myReadFile.eof())
        {
            getline(myReadFile, str);

            if (str == "<tr>")
            {            
                getline(myReadFile, str); //get the next line cause thats where the <td><b>Outage Message</b></td> is.
                size_t foundIndex = str.find(rowHtmlCloseTags); //does the sought string exist in this this line?
                if (foundIndex != str.npos) //if not no position
                    str.replace(foundIndex, rowHtmlCloseTags.size(), replacement); //replace the string
                else
                    std::cout << "Oops.. didn't find " << rowHtmlCloseTags << std::endl; //else throw a bitch

                foundIndex = str.find(rowHtmlOpenTags); //does the sought string exist in this this line?
                if (foundIndex != str.npos) //if not no position
                    str.replace(foundIndex, rowHtmlOpenTags.size(), replacement); //replace the string
                else
                    std::cout << "Oops.. didn't find " << rowHtmlOpenTags << std::endl; //else throw a bitch

                myMessages[i]=str;
                i++;
            }
        }
    }
    system("cls");
    i=0;
    while (i < 10)
    {
        cout << i << ") " << myMessages[i] << endl;
        i++;
        if (myMessages[i]=="")
        {
            break;
        }
    }
    myReadFile.close();
    cout << endl;
    cout << endl;
    cout << "Enter the message you would like to see on the reader board.\n";
    cout << "Or enter 911 to go back to the main menu: ";
    cin.ignore(1080);
    getline (cin,MessageToAdd);

    if (str == "911") //go back to the main menu
    {
        system("cls");
        mainMenu();
    }
    else //insert the message into a blank spot in the array
    {
        i=0;
        while (i < 10)
        {
            if (myMessages[i].empty())
            {
                myMessages[i]=MessageToAdd;
                break;
            }
            else
            {
                i++;
            }
        }
    }

    //now rebuild the htm file with the new array
    CreateHtmlFile(myMessages);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅唱ヾ落雨殇 2024-09-14 23:26:40

我会告诉你一件事,你的代码立即出了问题,不是你的具体问题,但仍然是一个棘手的问题。

我假设您的 mainMenu() 函数正在调用此函数。在这种情况下,您似乎会误解:

if (str == "911") //go back to the main menu
{
       system("cls");
       mainMenu();
}

将返回到您的菜单。它不会那样做。它要做的就是重新调用主菜单代码,最终您将耗尽堆栈空间。

我怀疑你应该做的是在 mainMenu() 中有一个循环,上面的代码应该只使用 return; 而不是调用 mainMenu()代码> 递归地。

事实上,我认为您应该将 MessageToAdd"911" 而不是 str 进行比较。


我要做的另一件事是将一些临时调试代码放入:

cout << "DEBUG A\n";
i=0;
while (i < 10)
{
    cout << "DEBUG B " << i << "\n";
    if (myMessages[i].empty())
    {
        cout << "DEBUG C\n";
        myMessages[i]=MessageToAdd;
        break;
    }
    else
    {
        i++;
        cout << "DEBUG D " << i << "\n";
    }
    cout << "DEBUG E\n";
}
cout << "DEBUG F\n";

并查看打印的内容。当然,您可以在调试器中跟踪执行情况,但这需要您自己完成这项工作。如果您只是发布输出(如果输出很大,则为前 100 行),那么我们可能可以轻松地告诉您出了什么问题。


实际上,我认为你的问题是 cin.ignore 。当我运行你的代码时,没有任何效果,无论是 Test 还是 Test Test Test 。这是因为它忽略了我尝试输入的前 1080 个字符。当您将这些语句更改为:

cin.ignore(1);
getline (cin,MessageToAdd);
cout << MessageToAdd << "\n";

并且输入 test 时,您将获得 est 输出。

取出ignore行并重试。我不确定这一点,因为您似乎表明 Test 有效,但我不认为这是正确的。


因此,这就是您需要做的(至少):

  • 完全摆脱 cin.ignore
  • 使用 return 而不是 mainMenu()
  • 使用 if (MessageToAdd == "911") 而不是 if (str == "911")
  • 让我们知道事情进展如何。

I'll tell you one thing that's immediately wrong with your code, not your specific problem but a hairy one nonetheless.

I'm presuming that your mainMenu() function is calling this one. In that case, you appear to be under the misapprehension that:

if (str == "911") //go back to the main menu
{
       system("cls");
       mainMenu();
}

will return to your menu. It will not do that. What it will do is to call your main menu code afresh and eventually you will run out of stack space.

I suspect that what you should be doing is having a loop in mainMenu() and that code above should just use return; rather than calling mainMenu() recursively.

That and the fact that I think you should be comparing MessageToAdd against "911" rather than str.


Another thing I would do would be to put some temporary debug code in:

cout << "DEBUG A\n";
i=0;
while (i < 10)
{
    cout << "DEBUG B " << i << "\n";
    if (myMessages[i].empty())
    {
        cout << "DEBUG C\n";
        myMessages[i]=MessageToAdd;
        break;
    }
    else
    {
        i++;
        cout << "DEBUG D " << i << "\n";
    }
    cout << "DEBUG E\n";
}
cout << "DEBUG F\n";

and see what gets printed. Of course, you could trace the execution in a debugger but that would require you to do the work yourself. If you just post the output (first 100 lines if it's huge), then we can probably tell you what's wrong easily.


Actually, I think your problem is the cin.ignore. When I run your code, nothing works, neither Test nor Test Test Test. That's because it's ignoring the first 1080 characters I'm trying to input. Proof can be seen when you change those statements to:

cin.ignore(1);
getline (cin,MessageToAdd);
cout << MessageToAdd << "\n";

and you get est output when you enter test.

Take out the ignore line and try again. I'm not certain of this since you seem to indicate that Test works but I can't see this as being correct.


So here's what you need to do (at a bare minimum):

  • get rid of the cin.ignore altogether.
  • use return rather than mainMenu().
  • use if (MessageToAdd == "911") instead of if (str == "911").
  • let us know how it goes then.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文