Hang Dian ACM1062 String Input and Output

Reference source: https://blog.csdn.net/always2015/article/details/45364713

Title: http://acm.hdu.edu.cn/showproblem.php?pid=1062

Personal problem: I only understand the input and output of a single integer, but I don't know much about strings, I don't know it at all, forget it when I remember it.... Lack of practice and basic knowledge

God code:

#include<stdio.h>
#include<string>
#include<iostream>
using namespace std;

int main(){
	int t,length,count=0;
	string input_str;
	cin>>t;
	getchar();
	for(int i=0;i<t;i++){
		getline(cin,input_str);//Store the string in string
		length=input_str.size();//Get the length of the string
		input_str[length]=' ';//Add a null character at the end of the string, and make an end judgment later
		for(int j=0;j<=length;j++){
			if(input_str[j]!=' ')
				++count;
			else{
				for(int k=j-1;k>=j-count;k--)
					cout<<input_str[k];
			if(j!=length)
				cout<<" ";
			count=0;
			}
		}
		cout<<endl;
	}
	return 0;
}

Code yourself according to the code above:

The general and specific meaning can be understood, but some places are prone to errors

#include<iostream>
#include<string>
#include<cstdio>
using namespace std;

int main(){
	int N,count=0;
	string str;
	cin>>N;
	getchar();//Accommodates '\n';
	while(N--){
		
		getline (cin, str);
		int length=str.size();
		str[length]=' ';
		
		for(int i=0;i<=length;i++){      //不要写成 i<length
			
			if(str[i]!=' ')
				count++;
				
			else{
				
				for(int j=i-1;j>=i-count;j--)
					cout<<str[j];
				if(i!=length)
					cout<<" ";
				count=0;
			}
		}
		cout<<endl;
	}
	return 0;
}

Okami analysis:

This question is not difficult. The main thing is to pay attention to the access method of the string, and more than half of it is successful. Moreover, how to read a single word and then output it in reverse is also the key. When inputting a string, I use the getline() function. The parameters of this function are an input and a string object. The function reads the content from the given input stream until it encounters a newline (note that the newline is also read come in), and then read all the content into the string object (note that the newline character is not stored), getline() will end the reading operation and return the result as long as it encounters a newline character, even if the input at the beginning is The same goes for newlines. If the input is a newline character at the beginning, then the result is an empty string

Guess you like

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