Summary of the usage of strings with spaces in C/C++

In C/C++, the traditional input stream scanf("%s",&str) and cin>>str will return the string before the space when a space is encountered. But in many applications, we need to contain spaces in the string at the same time, so the previous two methods are not available now. What are the input stream processing methods provided in C/C++? Here are a few common methods I have summarized:

(1)gets(char *str)

         Need to include header file #include <stdio.h>

(2)scanf("%[^\n]]",str)

       Need to include the header file #include <stdio.h>, this method requires a certain understanding of regular expressions, for example: scanf("%[az AZ 0-9]",str) means that only the input is uppercase and lowercase letters and numbers.

(3)getline(cin,string str)

       Need to include the header file #include <string>, because getline is a member object of the string class, such as string::getline, where the first parameter is required to be a reference to the input stream object &istream.

      If you need to convert to char*, string encapsulates string operations in C++. To sum up, there are three ways to convert string to character array or pointer:

(a)c_str()

          string str="hi,girls!";
          char *p=str.c_str();

(b)data()

          string str="hello";
          char *p=str.data();

(c)copy(p,len,start)

        string str="howareyou";
         char pStr[40];
         str.copy(pStr,7,0); //7 means copy several characters, 0 means copy position
         *(pStr+7)='\0'; //Here you need to manually add the terminator

(4)cin.getline(char *str, int maxnum)

       Need to include the header file #include <iostream>, because the getline here is a member object of the input stream, such as: istream::getline.

Here is the test case code:

#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
	char str[100];
	string str1;
	//cin>>str;
	//scanf("%s", &str);
	//printf("%s", str);
	//scanf("%[a-z A-Z 0-9]",str);
	//scanf("%[^\n]]",str);
	//getline(cin,str1);
	//gets(str);
	//cin.getline(str, 10);
	
	cout<<str<<endl;
	system("pause");
	return 0;	
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324972372&siteId=291194637