由于某种原因,它会跳过第一个输入,直接跳到第二个输入。
#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;
}
它只允许输入一个字符串
答案 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
刷新字符,或者在某些实现中添加换行符。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;
}
}