簡體   English   中英

從用戶獲取c ++中的字符串並顯示它

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

我該怎么做??

它嘗試了這段代碼:

  char num[10];

  printf("Enter num:");

  scanf_s ("%s", &num);

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

請忽略“ num”。.我使用VS 2013,而我唯一包含的庫是“ stdafx.h”

參見std::getline

在C ++中,請勿使用printf ,而應使用std::cout 不要使用char[] ,請使用std::string

如果您選擇了項目類型(例如控制台應用程序)並將其編譯為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;
}

您不使用c ++中的“字符串”而不是char數組。 它易於操作和維護,並且具有許多內置算法,因此更加簡單有效。

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

您可以使用printf或scanf。 那完全可以

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM