簡體   English   中英

fscanf無法正確使用字符串

[英]fscanf doesn't work correctly with string

我的應用程序有一個簡單的問題。 fscanf收集整個單詞,但是大小(長度)等於currentName的默認大小。 如果currentName的默認長度值currentName單詞的長度,則該單詞被剪切。

例如:

如果currentName =“ 123”,則fscanf將返回“ Art”而不是“ Arthur”。

要么

如果currentName =“ 123456789”,則fscanf將返回“ Arthur 89”而不是“ Arthur”。

文件“ list.txt”包含以下行:

Arthur 30 1550
Ben 32 2100
Charlie 25 1850
Danny 46 2400
Edward 35 2750

我應該改變什么來解決這個問題? 我必須使用fscanf而不是fstream。

#include <iostream>
#include <stdio.h>
#include <string>
#include <stdlib.h>
using namespace std;
class Worker
{
private:
    string name;
    int age;
    double salary;
public:
    Worker()
    :name(""),age(99),salary(0)
    {}
    Worker(string name, int age, double salary)
        :name(name),age(age),salary(salary)
    {}
    void showVaulues()
    {
        cout<<endl;
        cout<<"Name:\t"<<name<<endl;
        cout<<"Age:\t"<<age<<endl;
        cout<<"Salary:\t"<<salary<<endl;
    }
};
int main()
{
    FILE *myfile=NULL;
    string currentName="123456789";
    int currentAge=0;
    double currentSalary=999999;
    Worker *ptr=NULL;
    myfile=fopen("list.txt","r");
    while (feof(myfile) == 0)
    {
        fscanf(myfile,"%s %d %lf\n",&currentName[0],&currentAge,&currentSalary);
        ptr=new Worker(currentName,currentAge,currentSalary);
        ptr->showVaulues();
    }
    system("pause");
}

您不能像在此處嘗試那樣直接修改std::string的內部緩沖區。 要讀取string ,請使用流:

std::ifstream in ("list.txt");
int >> currentname >> currentAge >> currentSalary;

如果確實需要使用fscanf ,請改用足夠大的std::vector<char>並將其像C風格的字符串一樣使用。

scanf %s掃描到char數組中,而不是std::string

std::string是通過struct { size_t length; char* buffer; } struct { size_t length; char* buffer; } struct { size_t length; char* buffer; } ,因此寫入buffer實際上會更改字符串。 但是,由於它明確跟蹤其長度,因此像字符串數組中的字符串一樣,不會將字符串末尾的'\\0'視為終止符。

您可以掃描到一個char數組中,但是執行此操作的C ++ ish方法是使用std::ifstream

暫無
暫無

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

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