zoukankan      html  css  js  c++  java
  • 关于C中字符串的输入和输出使用的函数不同所造成的影响

    今晚学习了一下字符数组的应用,根据要求(输入一行字符,统计有多少单词)编写几行代码,如下:

    #include<math.h>
    #include <stdio.h>
    #include <string.h>
    void main()
    {
    	char word[100];
    	int i,j;
    	i=0;
    	gets(word);
    	for(j=0;j<100;j++)
    	{   
    		if(word[j]=='')
    			break;
    		else if(word[j]!=' '&&word[j+1]==' '||word[j]!=' '&&word[j+1]=='')
    		  i++;
    		
    	}
    	printf("all the word is %d
    ",i);
    }
    

    之前在gets(word)的位置,我用的是scanf();但是死活都无法得出结果。经过查阅发现,字符串的输入和输出函数是有一定的区别的:

    gets()与scanf(“%s”):

     ① gets遇回车时结束输入。也就是说,gets可以接受回车前的任何输入。

                scanf不同,遇到回车、空格、制表符就结束输入。

                例如像这个字符串:”I am a student;

                如果要一次性的接受全部的字符串,要用gets。

             ② 输入结束后,gets的回车不会留在缓冲区;而scanf的空格、回车仍然会留在缓冲区。

     Puts()与printf(“%s”):

             ① puts函数只用来输出字符串,参数可以是字符串,也可以是存放字符串的数组名。

                Printf(“%s”)其参数也可以是是字符串,或者是存放字符串的数组名。

             ② puts函数输出字符串后会自动加换行,而printf(“%s”)不会。

                Puts(a)与scanf(“%s ”,a)等效.


  • 相关阅读:
    LeetCode "Palindrome Partition II"
    LeetCode "Longest Substring Without Repeating Characters"
    LeetCode "Wildcard Matching"
    LeetCode "Best Time to Buy and Sell Stock II"
    LeetCodeEPI "Best Time to Buy and Sell Stock"
    LeetCode "Substring with Concatenation of All Words"
    LeetCode "Word Break II"
    LeetCode "Word Break"
    Some thoughts..
    LeetCode "Longest Valid Parentheses"
  • 原文地址:https://www.cnblogs.com/JSD1207ZX/p/9386269.html
Copyright © 2011-2022 走看看