在比较字符串时出现问题

having issues comparing strings

本文关键字:问题 比较 字符串      更新时间:2023-10-16

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

#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 timesn";
    else
        cout << "The two strings you entered are not the samen";
    system("pause");
        return 0;
}
int main()
{
    stringWork();
    return 0;
}

它只允许输入一个字符串

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

修复如下代码:

#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;
    }
}