我正在尝试制作一些东西,所以你输入一个文件名,然后发短信写入文件,但是当我尝试编译它时,它说:
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 ++很新,不知道这意味着什么。另外我不确定如何使函数返回一个数组,所以我猜对了。任何人都可以帮忙吗?
答案 0 :(得分:2)
可能你写了类似的东西:
fstream filetoopen;
std::cin>>filetoopen;
打开用户指定文件的fstream
。这不是它的工作方式:您必须读取包含文件名的字符串,然后使用fstream
或open
方法的构造函数打开文件:
std::string fileName;
std::getline(cin, fileName);
std::fstream fileStream(fileName.c_str());
答案 1 :(得分:1)
fstream filetoopen;
cin >> filetoopen;
这是错误的,您无法从标准输入读取流。您可以将文件的名称读取为字符串,然后使用该名称打开文件流。