简体   繁体   English

从用户获取c ++中的字符串并显示它

[英]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" 请忽略“ num”。.我使用VS 2013,而我唯一包含的库是“ stdafx.h”

See std::getline . 参见std::getline

In C++, don't use printf , use std::cout . 在C ++中,请勿使用printf ,而应使用std::cout Don't use char[] , use std::string . 不要使用char[] ,请使用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 如果您选择了项目类型(例如控制台应用程序)并将其编译为C ++程序,则代码可以采用以下方式

#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. 您不使用c ++中的“字符串”而不是char数组。 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. 您可以使用printf或scanf。 Thats completely ok 那完全可以

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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