在比较字符串时出现问题
having issues comparing strings
由于某种原因,它跳过第一个输入,直接进入第二个输入。
#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;
}
}
相关文章:
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 关于比较两个无序数组并删除 a[] 中可以在 b[] 中找到的元素的问题
- std::max() 函数与定点实现的比较中的问题
- C++复杂情况的比较器通过参数问题
- 这种比较是否不一致(或者存在其他问题)?
- 将此类数据作为字符串进行比较时出现问题
- 关于没有比较的条件的问题
- 通过比较字符设置字符串时出现问题
- 无符号int的比较始终是正确的(NPOS问题?)
- 比较两个字符的问题
- (C++) 学习向量 - 编码/输入流终止/比较向量的问题
- C++ lower_bound比较功能问题
- 比较答案键(C )的字符串的问题
- C++ std:字符串比较编纂问题
- 比较字符串(arduino)时出现问题
- 将 char * 与字符串文本进行比较时出现问题
- MAP和比较类别的C 问题
- 排序功能不起作用(字符串比较问题)
- 使用比较运算符和字符串比较函数读取文本文件的子部分时出现问题
- 使用具有自定义比较类型的关联容器时出现的问题