将C函数转换为C ++语言

问题描述 投票:0回答:2

由于这是我第一次接触C编程语言,所以我不清楚如何将一段代码转换为C ++。我知道该代码可以在C ++中使用,但我想专门研究C ++语言的语法。

这是我的代码:

FILE *f;
char name[10],surname[10],j[10];
f=fopen("Marks.txt","r");
fscanf(f,"%d",&n);

我想使用以下方式打开文件:

ifstream input;
input.open("Marks.txt");

但是然后我不知道要用什么代替fscanf函数,因为我不能再使用FILE * f;

c++ file syntax
2个回答
0
投票

这是C ++的方法,尽管从技术上讲,您仍然可以使用该C代码。

#include <ifstream>

int main() {
  std::string str;
  int i;
  double d;
  char c_str[10];

  std::ifstream input;
  input.open("Marks.txt");
  input >> str; // reads a line of text into str
  input >> i;   // assuming there is a valid integer after the first line, reads it into i
  input >> d;   // assuming there is a valid double after that, reads it into d
  // reads up to 9 characters + a '\0', stopping if it reaches a space
  input.get(c_str, 10-1, ' ');
  // etc.
}

0
投票

喜欢这个:

int main()
{
    // Let the constructor handle opening the file.
    std::ifstream input("Marks.txt");
    int n = 0;
    std::string s;
    double d = 0;
    // Read an int, followed by a string, followed by a double.
    if (input >> n >> s >> d)
    {
        std::cout << "Success!\n";
    }
    else
    {
        std::cout << "Failure!\n";

    }
    // The destruction of 'input' will close the file.
}
© www.soinside.com 2019 - 2024. All rights reserved.