C与C++中输入字符串的方法

来源:互联网 发布:网络优化论文3000字 编辑:程序博客网 时间:2024/05/23 12:24

1、C语言中输入字符串

(1)使用scanf_s函数

#include "stdafx.h"

#include "stdio.h"

#include "string.h"

 

intmain()

{

    char a[10], b[10];

    scanf_s("%s", a, sizeof(a));    //要取地址符&和不要都可以

    scanf_s("%s", &b,sizeof(b));

    printf("输入的字符串a是:%s\n", a);

    printf("输入的字符串b是:%s\n", b);

    int c;

    scanf_s("%d", &c);

   

   return0;

}

(2)使用gets_s()函数

#include "stdafx.h"

#include <stdio.h>

#include "string.h"

#include<stdlib.h>

 

intmain()

{

    char a[10], b[10];

    //scanf_s("%s", a, sizeof(a));     //要取地址符&和不要都可以

    //scanf_s("%s", b,sizeof(b));

    //printf("输入的字符串a是:%s\n", a); 

    //printf("输入的字符串b是:%s\n", b);

    gets_s(a);

    printf("输入的字符串a是:%s\n", a);

    system("pause");

   return0;

}


2、C++中输入字符串的方法

(1)使用getline()函数

#include "stdafx.h"

#include <iostream>

#include <string>

using namespace std;

intmain()

{

    char a[10], b[10];

    cin.getline(a,10);

    cin.getline(b,10);

    cout<< "a字符串的是:"<<a<< endl;

    cout<< "b字符串的是:"<<b<< endl;

    int d=0;

    cin>> d;

    return 0;

}


(2)使用get()函数

#include "stdafx.h"

#include <iostream>

#include <string>

using namespace std;

intmain()

{

    char a[10], b[10];

    cin.get(a,10);

    cin.get(b,10);

    cout<< "a字符串的是:"<<a<< endl;

    cout<< "b字符串的是:"<<b<< endl;

    int d=0;

    cin>> d;

    system("pause");

    return 0;

}


(3)使用string类

#include "stdafx.h"

#include <iostream>

#include <string>

using namespace std;

intmain()

{

    /*char a[10], b[10];

    cin.get(a,10).get();

    cin.get(b,10);

    cout<< "a字符串的是:"<<a <<endl;

    cout<< "b字符串的是:"<<b <<endl;

    intd=0;

    cin>> d;*/

    string str;

    getline(cin,str);

    cout<< "字符串str为:"<<str<< endl;

    system("pause");

    return 0;

}


原创粉丝点击