将行写入.txt文件c ++

时间:2015-11-29 04:36:23

标签: c++ fileoutputstream

对于你们所有的程序员!我想弄清楚为什么我的程序不起作用。我很难过!我正在尝试编写一个程序来打开一个名为“CSC2134.TXT”的文本文件进行输出,然后从控制台接受文本行并将文本行写入文件并使用任何空字符串来结束程序。这就是我所拥有的:

#include <iostream> 
#include <fstream> 
#include <cstring> 
using namespace std; 

int main() 
{ 
 char str[80]; 

 ofstream file1; 
 file1.open("CSC2134.txt"); 

 if (file1 == 0) 
  { 
    cout << "error opening CSC2134.txt" << endl; 
    return 1; 
  } 
 else 
  { 
   file1 << "Enter some text:\n"; 
   while(strlen(str) != '\n') 
    { 
     file1 << cin.getline(str,80); 

     if(strlen(str) == 0) 
     break; 
    } 
   file1.close(); 
  } 

  return 0; 
} 

我正在试图找出我收到错误消息的原因。

3 个答案:

答案 0 :(得分:1)

你有一些错误:

您正在输出&#34;输入一些文字&#34;到文件而不是cout。

您没有以正确的方式循环,以便仅在用户的输入为空字符串时退出应用程序。

这是更正后的版本:

#include <iostream> 
#include <fstream> 
#include <cstring> 
using namespace std; 

int main() 
{ 
 char str[80]; 

 fstream file1; 
 file1.open("CSC2134.txt"); 

 if (!file1.is_open()) 
  { 
    cout << "error opening CSC2134.txt" << endl; 
    return 1; 
  } 
 else 
  { 
   std::cout<< "Enter some text:\n"; 

   cin.getline(str,80);
   while((strlen(str) != 0) ) 
    { 

     file1 << str;
     cin.getline(str,80);

    } 
   file1.close(); 
  } 

  return 0; 
} 

<强>更新

改为运行它,告诉我运行程序时输出是什么:

#include <iostream> 
#include <fstream> 
#include <cstring> 
using namespace std; 

int main() 
{ 
 char str[80]; 

 ofstream file1; 

 file1.exceptions ( ifstream::failbit | ifstream::badbit );
 try {
  file1.open("CSC2134.txt", fstream::in | fstream::out | fstream::binary);
 }
 catch (ifstream::failure e) {
    cout << "Exception opening/reading file"<< e.what();
  }

 if (!file1.is_open()) 
  { 
    cout << "error opening CSC2134.txt" << endl; 
    return 1; 
  } 
 else 
  { 
   std::cout<< "Enter some text:\n"; 

   cin.getline(str,80);
   while((strlen(str) != 0) ) 
    { 

     file1 << str;
     cin.getline(str,80);

    } 
   file1.close(); 
  } 

  return 0; 
} 

答案 1 :(得分:1)

这是一个错误和纠正不良行为的版本:

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>     // EXIT_FAILURE
using namespace std;

int main()
{
    auto const filename = "CSC2134.txt";
    ofstream file1( filename );
    if( file1.fail() )
    {
        cerr << "!Error opening " << filename << endl;
        return EXIT_FAILURE;
    }

    string str;
    cout << "Enter some text, with a blank last line:\n";
    while( getline( cin, str ) && str != "" )
    {
        file1 << str << endl;
    }
}

我个人会写and而不是&&,但是初学者不能正确配置编译器来接受它。问题主要在于Visual C ++。可以使用<iso646.h>的强制包含来使其接受标准andornot

提示:我使用免费的 AStyle 程序将缩进修复为更清晰的内容。

答案 2 :(得分:1)

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main (){
    ofstream myfile("CSC2134.txt");

    if(myfile.is_open())
    {
        string str;
        do{
            getline(cin, str);
            myfile<<str<< endl;
        }while(str!="");
        myfile.close();
    }
    else cerr<<"Unable to open file";

    return 0;
}
相关问题