0

我正在尝试做一些事情,因此您输入文件名,然后输入要写入文件的文本,但是当我尝试编译它时,它会说:

files.cc: In function ‘int main()’:
files.cc:11: error: ambiguous overload for ‘operator>>’ in ‘std::cin >> filetoopen’
/usr/include/c++/4.2.1/istream:131: note: candidates are: std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>& (*)(std::basic_istream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>] <near match>
/usr/include/c++/4.2.1/istream:135: note:                 std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_ios<_CharT, _Traits>& (*)(std::basic_ios<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>] <near match>
/usr/include/c++/4.2.1/istream:142: note:                 std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>] <near match>
/usr/include/c++/4.2.1/istream:250: note:                 std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_streambuf<_CharT, _Traits>*) [with _CharT = char, _Traits = std::char_traits<char>] <near match>
files.cc:14: error: no match for ‘operator>>’ in ‘std::cout >> text’
files.cc:16: error: conversion from ‘std::fstream’ to non-scalar type ‘std::ofstream’ requested
files.cc: In function ‘char* openfile(std::fstream, char*)’:
files.cc:21: error: no matching function for call to ‘std::basic_fstream<char, std::char_traits<char> >::open()’
/usr/include/c++/4.2.1/fstream:780: note: candidates are: void std::basic_fstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]

#include <iostream>
#include <fstream>

using namespace std;

char* openfile(ofstream file, char* words);

int main()
{
  fstream filetoopen;
  char* text;
  cout << "Enter the name of a file to write to." << endl;
  cin >> filetoopen;
  cout << "Now write somthing to the file." << endl;
  cin >> text;
  openfile(filetoopen, text);
}

char * openfile (fstream file, char* words)
{
  file.open();
  file << words << endl;
  file.close();

  return words;
}

我对 C++ 很陌生,不知道这意味着什么。另外我不确定如何让函数返回一个数组,所以我有点猜到了。任何人都可以帮忙吗?

4

2 回答 2

2

可能你写了类似的东西:

fstream filetoopen;
std::cin>>filetoopen;

打开fstream用户指定的文件。这不是它的工作方式:您必须读取包含文件名的字符串,然后使用构造函数fstream或其open方法打开文件:

std::string fileName;
std::getline(cin, fileName);
std::fstream fileStream(fileName.c_str());
于 2012-07-14T16:03:59.053 回答
1
fstream filetoopen;
cin >> filetoopen;

这是错误的,您不能从标准输入中读取您可以将文件名读取为字符串,然后使用该名称打开文件流。

于 2012-07-14T16:05:05.810 回答