有比较字符串的问题

时间:2014-04-10 19:17:49

标签: c++

由于某种原因,它会跳过第一个输入,直接跳到第二个输入。

#include<iostream>
#include<string>
using namespace std;

int stringWork()
{
    const int LENGTH = 40;
    char firstString[LENGTH], secondString[LENGTH];
    cout << "Enter First String: ";
    //it skips over this following line
    cin.getline(firstString, LENGTH);
    cout << "Enter Another String: ";
    cin.getline(secondString, LENGTH);

    if (strcmp(firstString, secondString) == 0)
        cout << "You entered Same string two times\n";
    else
        cout << "The two strings you entered are not the same\n";
    system("pause");
        return 0;
}

int main()
{
    stringWork();
    return 0;
}

它只允许输入一个字符串

2 个答案:

答案 0 :(得分:1)

这段代码在我的机器上运行得很好。但是,请将#include <string>更改为#include <string.h>#include <cstring>,然后添加#include <stdlib.h>#include <cstdlib>

答案 1 :(得分:0)

修复如下代码:

#include <iostream>
#include <string>

void stringWork()
{
    const int LENGTH = 40;
    char firstString[LENGTH], secondString[LENGTH];
    std::cout << "Enter First String: " << std::flush;
    std::cin.getline(firstString, LENGTH);
    std::cout << "Enter Another String: " << std::flush;
    std::cin.getline(secondString, LENGTH);

    if (strcmp(firstString, secondString) == 0) {
        std::cout << "You entered Same string two times." << std::endl;
    } else {
        std::cout << "The two strings you entered are not the same." << std::endl;
    }
}

int main()
{
    stringWork();
    return 0;
}

关于我的代码版本的一些注释:

  • 请不要使用using namespace std
  • 使用std::flush刷新输出流中的字符。这是必要的,因为通常只使用std::endl刷新字符,或者在某些实现中添加换行符。
  • 避免像你一样混合使用C和C ++代码。使用std::getline方法直接将一行读入std::string。如下一个例子所示。
  • 请关注您的代码风格,尤其是在公开发布时。

更好的实现将避免任何C代码并仅使用C ++:

#include <iostream>
#include <string>

void stringWork()
{
    std::cout << "Enter First String: " << std::flush;
    std::string firstString;
    std::getline(std::cin, firstString);
    std::cout << "Enter Another String: " << std::flush;
    std::string secondString;
    std::getline(std::cin, secondString);

    if (firstString == secondString) {
        std::cout << "You entered Same string two times." << std::endl;
    } else {
        std::cout << "The two strings you entered are not the same." << std::endl;
    }
}