簡體   English   中英

ScanF和C ++中的字符串

[英]Scanf and strings in c++

我有一個非常簡單的程序。

#include <stdio.h>
#include <string>
using namespace std;
struct scholar{
    int number;
    string fam;
    int ocen;
};


int main(){
    int len;

    printf("vvedite n");
    scanf("%d", &len);
    scholar *barr= new scholar[len];

    for(int i=0; i<len; i++){
        printf("Nomer studenta ");
        scanf("%d", &barr[i].number);
        printf("\nFamilia ");
        scanf("%s", barr[i].fam);
        printf("\nOcenka");
        scanf("%d", &barr[i].ocen);
    }
        delete [] bar;

但是在網上,我想輸入家庭的地方,有一個警告:

warning: format specifies type 'char *' but the argument has type 'string'
(aka 'basic_string<char>') [-Wformat].

有什么建議如何解決嗎?

您無法scanfstd::string ,C函數不知道什么是C ++實現。 您可以使用std::getline

#include <string>
#include <iostream>

std::getline(std::cin, barr[i].fam);

另外,不要混合使用C ++代碼的C代碼,並應避免new可能的話,使用矢量scholar來代替。 樣品:

std::vector<scholar> barr;

'scanf'是在stdio.h中定義的,它是C庫而不是c ++庫,因此您可以將類型'char *'自動轉換為'string'。 您可以使用其他輸入IO流功能,而不是'scanf'。

暫無
暫無

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

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