简体   繁体   中英

Getting a string in c++ from user, and displaying it

how do i do it??

it tried this code:

  char num[10];

  printf("Enter num:");

  scanf_s ("%s", &num);

  printf("\n%s \n", num);

ignore 'num' please.. i use VS 2013, and my only included library is "stdafx.h"

See std::getline .

In C++, don't use printf , use std::cout . Don't use char[] , use std::string .

If you selected the type of the project like console application and compile it as a C++ program then the code can look the following way

#include "stdafx.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
    char s[100];

    std::cout << "Enter a sentence: ";
    std::cin.getline( s, sizeof( s ) );

    std::cout << "You entered \"" << s << "\"\n";

    return 0;
}

You don't you use the "string" in c++ instead of the char array. Its easy for operation and maintenance, plus its much more simple and efficient with so many built in algorithms.

string num ;// instead of char num[10];
cout<<"Enter num";
cin>>num;
cout<<num;

you may use printf or scanf. Thats completely ok

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM