如何使忽略功能也删除定界符

问题描述 投票:0回答:1

我想获取10个字符并将其存储在cstring中,而忽略其余字符,但是我对此有疑问。该程序下次不会停止输入。如何使它停止并让我再次进入。

#include <cstring>
#include <iostream>

using namespace std;

int main()
{

   char arr[11] = " "; //This is a cstring
   string x; //will test with this variable

   cout <<"Enter 10 character, rest will be ignored: \n";
   cin.getline(arr, 10,'\n');  
   cin.ignore();

   cout <<"Testing..\n";
   cin >>x;            //Should make the program halt

   cout <<arr <<endl;
   cout <<x;

}
c++ c-strings
1个回答
0
投票

cin.getline(arr, 10,'\n')将最多输出9个字符,而不是10个字符,如果在达到9个字符之前读取了换行符,它将停止输出。如果要接收10个字符,则需要将count参数设置为11-arr的完整大小-要包含10个字符的空间+空终止符。

此后不带任何参数调用cin.ignore()将仅忽略1个字符。因此,如果用户键入的字符超过count+1个,则您不会全部忽略它们。如果读取期间未达到换行符,则应告诉cin.ignore()忽略下一个换行符之前的所有字符。

尝试以下方法:

#include <iostream>
#include <string>
#include <limits>

using namespace std;

int main()
{
    char arr[11]; //This is a cstring
    string x; //will test with this variable

    cout << "Enter 10 character, rest will be ignored: \n";
    if (cin.getline(arr, 11, '\n'))
    {
        // <= 10 characters w/ line break were read
    }
    else
    {
        if (cin.fail() && !cin.bad()) // exactly 10 characters w/o a line break were read, ignore the rest...
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    }

   cout << "Testing..\n";
   cin >> x;            //Should make the program halt

   cout << arr << endl;
   cout << x;
}

也就是说,这是C ++,而不是C。改用std::getline()会更容易,例如:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str; //This is a c++ string
    string x; //will test with this variable

    cout << "Enter 10 character, rest will be ignored: \n";
    getline(cin, str);

    if (str.size() > 10)
        str.resize(10);

    cout << "Testing..\n";
    cin >> x;            //Should make the program halt

    cout << str << endl;
    cout << x;
}
© www.soinside.com 2019 - 2024. All rights reserved.