2016-12-28 53 views
-2

我使用getchar()和loop來獲取文本,並使用fputc()放入文本文件,但它總是在寫入文本文件後將第一行留空。當字符輸入是點(。)時,循環停止。我如何刪除第一行?fputc在插入文本之前將第一行留空

更新(12/29/2016):我用DevC++和代碼運行良好,沒有創建一個空的空白,但我的VisualStudio2015有問題。

舉例:創建一個名爲test.txt

輸入文件:這是一個文本。

輸出:(在文本文件)

[空行]

這是一個文本

void writeFile(char *fileName){ 
    FILE *fp; 
    fp = fopen(fileName, "wt"); //write text 
    if (fp == NULL) { 
     cout << "Failed to open" << endl; 
     fclose(fp); 
    } 
    else { 
     int i = 0; 
     char c = '\0';   
     cout << "Enter a text and end with dot (.): "; 
     fflush(stdin); 
     //c = getchar(); 
     while (c != '.') { 
      fputc(c, fp); 
      c = getchar(); 
     } 
     cout << "Written successfully" << endl; 
     fclose(fp); 
    } 
} 
+2

嘗試扭轉)的的fputc的順序(和的getchar()線。 –

+1

'fflush(stdin)'不會刷新輸入流,而是用於輸出流。嘗試'fflush(stdout)'。 –

+1

爲什麼使用C++流('cin','cout')和C風格流('FILE *')? *不要跨越流。*使用'std :: ifstream'作爲文件。 –

回答

1

出於好奇,是那裏的一個原因C函數?在C++中做這樣的事情會更適合於使用流,如:

#include <iostream> 
#include <fstream> 

using namespace std; 

void writeFile(const char *fileName) 
{ 
    ofstream writeToFile; 
    writeToFile.open(fileName); 
    if (!writeToFile.is_open()) { 
     cout << "Failed to open" << endl; 
     return; 
    } else { 
     string stringToWrite{""}; 
     char c = '\0';   
     cout << "Enter a text and end with dot (.): "; 
     while (c != '.') { 
      std::cin >> c; 
      stringToWrite += c; 
     } 
     writeToFile << stringToWrite << endl; 
     cout << "Written successfully" << endl; 
     writeToFile.close(); 
    } 
} 

int main() 
{ 
    const char *fileName="test.txt"; 
    writeFile(fileName); 
    return 0; 
} 

,或者可選地:

#include <iostream> 
#include <fstream> 

using namespace std; 

void writeFile(const char *fileName) 
{ 
    ofstream writeToFile; 
    writeToFile.open(fileName); 
    if (!writeToFile.is_open()) { 
     cout << "Failed to open" << endl; 
     return; 
    } else { 
     string stringToWrite{""};  
     cout << "Enter text and press return: "; 
     getline(cin, stringToWrite); 
     writeToFile << stringToWrite << endl; 
     cout << "Written successfully" << endl; 
     writeToFile.close(); 
    } 
} 

int main() 
{ 
    const char *fileName="test.txt"; 
    writeFile(fileName); 
    return 0; 
} 
+0

??定義「更適合」。 –

+0

@KarolyHorvath爲C++編譯器編寫慣用的C++更好。 –

+0

編譯器不關心。 *人(有時候)。 –

0

c是0在第一通,因此空行。

變化while循環

while((c = getchar()) != EOF) 
    { 
     if(c == '.') 
     break; 
    } 

它看起來有點奇怪,但是慣用的用於C.從流中讀取字符

+0

嗯,我只是在我的帖子中添加了關於不同IDE的不同結果的信息。我只有在VisualStudio2015上有問題,並且我嘗試修改我的爲什麼循環作爲你的建議,但它仍然沒有工作。 –

相關問題