【问题标题】:C++ cout prints out same string a few timesC++ cout 多次打印出相同的字符串
【发布时间】:2013-12-11 21:44:36
【问题描述】:

我的代码有一个 if else 语句,用于验证输入是否是一个充满字母字符的字符串。

代码有效,但cout << original << "\n"; 部分打印了 5 次结果。我认为问题的根源在于for (std::string::iterator it=original.begin(); it!=original.end(); ++it) 行,特别是++it 位。

下面是代码:

#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <locale>
#include <iostream>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{
    std::locale loc;
    std::string original;
    std::cout << "Welcome to the English to Pig Latin translator!\n";
    std::cout << "Type a word you wish to translate:\n";
    std::getline(std::cin, original);
    std::cout << "Your word: " << original << "\n";
    for (std::string::iterator it=original.begin(); it!=original.end(); ++it)
    {
        if (original.length() > 0 && std::isalpha(*it,loc) )
        {
            std::string word;
            std::transform(original.begin(), original.end(), original.begin(), ::tolower);
            cout << original << "\n";
        }
        else
        {
            std::cout << "Please enter a valid word." << std::endl;
        }
    }

    system("PAUSE");
    return 0;
}

此链接是我的 CLI 输出的屏幕截图: http://gyazo.com/5b9cea385794fecc39ed578b539a84c3

【问题讨论】:

    标签: c++ if-statement


    【解决方案1】:

    它打印了五次,因为“hello”有五个字符长。您的 for 循环为字符串中的每个字符运行一次。

    【讨论】:

    • 啊,好吧!涉及 for 循环的原因是因为这是我知道如何执行代码的 isalpha 部分的唯一示例。如果我在没有 for 循环的情况下执行此操作,只使用 if/else 语句并使用 ...&amp;&amp;isalpha(original)),则 Dev-C++ 编译器不喜欢它。
    • 如果你想查看整个字符串是字母数字还是类似的,看这个答案stackoverflow.com/questions/2926878/…
    【解决方案2】:

    您的代码不正确。它检查每个字符而不是整个字符串。

    改成:

    bool alphaString = true;
    for (std::string::iterator it=original.begin(); it!=original.end(); ++it)
        {
            if (! std::isalpha(*it,loc) )
            {
                std::cout << "Please enter a valid word." << std::endl;
                alphaString = false;
                break;
            }
        }
    if ( alphaString ) {  
      std::transform(original.begin(), original.end(), original.begin(), ::tolower);
      cout << original << "\n";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      相关资源
      最近更新 更多