输入多个字符串c++

Entering multiple strings C++

本文关键字:c++ 字符串 输入      更新时间:2023-10-16

下面的代码尝试用空格输入多个字符串,然后我需要在它们之间进行比较。我面临的问题是,它不能输入超出第一个字符串。我想这是输入缓冲区中剩余的"enter"导致这种行为,即跳过字符串的进一步输入。有什么建议来克服这个问题吗?

参考:如何在c++中使用空格?

编辑:清除和冲洗我尝试过,但仍然是同样的问题。我需要实现C风格的字符串函数,所以不能使用字符串类,函数strcmp等必须由我实现,而不是使用库函数。

int main()
    {
        char s[100];
        char s1[100];
        char s2[100];
        char* sub;
        struct countSpaces cs;

cout << "Enter a String : ";
cin.get( s, 100 );
std::cin.clear();
cs=count(s);
cout << s << " contains " << cs.letters << " letters and " << cs.spaces << " spaces" << endl;
cout << "Length of " << s << " is " << strlen(s) << endl;
cout << "Enter First String : ";
cin.get( s1, 100 );
std::cin.clear();
cout << "Enter second String : ";
cin.get( s2, 100 );
std::cin.clear();
        if( strcmp(s1,s2) )
        cout << s1 << " is equal to " << s2 << endl;
        else
        cout << s1 << " is not equal to " << s2 << endl;

        return 0;
        }
输出:

$ ./String
Enter a String : Herbert Schildt
Herbert Schildt contains 14 letters and 1 spaces
Length of Herbert Schildt is 15
Enter First String : Enter second String :  is not equal to
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s1 = "";
    string s2 = "";
    cout << "Enter first string > ";
    getline(cin, s1);
    cout << "Enter second string > ";
    getline(cin, s2);
    if(strcmp(s1,s2))
        cout << s1 << " is equal to " << s2 << endl;
    else
        cout << s1 << " is not equal to " << s2 << endl;
    // copy string s1 into C-String str
    char * str = new char [s1.length()+1];
    std::strcpy (str, s1.c_str());
    return 0;
}

std::cin.ignore(100,'n');做到了。