2016-03-28 117 views
-2

我试图读取一个随机文件(在mac-xcode上)并确定文档中字母k的实例。然后打印该数字作为输出文件。我的问题是outfile没有被写入,并且nums_k返回为0.我不确定ifstream是否工作不正确,或者ofstream需要建立不同的文件名。这是我的源代码。ifstream ofstream on mac

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

int main() { 

    ifstream infile("Users/bryanmichaelnorris/documents/extra credit assignment.docx"); 

    string line; 
    int numks = 0; 

    while (getline(infile,line)) {  
     int x = 0;   
     for (std::string::iterator it=line.begin(); it!=line.end(); ++it) {    
      if (line[x] == 'k') {     
        numks++;    
      }    
      x++;   
     }  
    }   

    infile.close();  
    ofstream outfile("number of k's.docx"); 
    outfile << "There are " << numks << " K's in the file." << endl; 
    outfile.close();   
    return 0; 
} 
+1

'“Users/...”',我会先在该名称的*开头*处加上一个'/'开始。如果你想验证你的输入文件是否正确打开,它肯定不会损害*测试它,而不是假设世界上所有的东西都是正确的。您可能还想研究输出文件的写入位置,因为在Xcode下运行时的当前工作目录通常与人们所认为的完全不同(但可以在模式编辑器中更改它)。 – WhozCraig

+0

@WhozCraig几乎肯定碰到了头部 – trojanfoe

+0

不要使用'.docx'扩展名来处理不是MS-Word文档的文件...如果您确实需要扩展名,也许'.txt'是一个好多了。如果输入文件也是MS-Word文件,那么我不会用这种方法计算字母'k',因为您可能会将'k'用于除文本本身之外的其他内容。 –

回答

0

为打开的文件添加验证。

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

int main() 
{ 
    const char * csInputFileNane="Users/bryanmichaelnorris/documents/extra credit assignment.docx"; 
    ifstream infile(csInputFileNane); 
     if (!infile.is_open()) { 
     cerr << "Cannot open file \""<<csInputFileNane<<'"'<<endl; 
     return -1; 
    } 
    string line; 

    int numks = 0; 

    while (getline(infile,line)) 
    { int x = 0; 
     for (std::string::iterator it=line.begin(); it!=line.end(); ++it)    { 
      if (line[x] == 'k') 
      { 
       numks++; 
      } 
      x++; 
     } 
    } 
    infile.close(); 
    const char *csOutFileName="number of k's.docx"; 
    ofstream outfile(csOutFileName); 
    if (!outfile.is_open()) { 
     cerr << "Cannot open file \""<<csOutFileName<<'"'<<endl; 
     return -1; 
    } 
    outfile << "There are " << numks << " K's in the file." << endl; 
    outfile.close(); 
    return 0; 

}