2016-05-11 41 views
0
#include "stdafx.h" 
#include <fstream> 
#include <iostream> 

using namespace std; 

int main() 
{ 
    char ch; 
    int a = 0; 
    int e = 0; 
    int i = 0; 
    int o = 0; 
    int u = 0; 

    std::ifstream file("myfile.txt", std::ifstream::in); 

    if (file.is_open()) 
    { 
     while (file.get(ch)) 
     { 
      if (ch == 'a') 
       a++; 
      if (ch == 'e') 
       e++; 
      if (ch == 'i') 
       i++; 
      if (ch == 'o') 
       o++; 
      if (ch == 'u') 
       u++; 
     } 

     std::cout << "Repetitions of a: " << a << std::endl; 
     std::cout << "Repetitions of e: " << e << std::endl; 
     std::cout << "Repetitions of i: " << i << std::endl; 
     std::cout << "Repetitions of o: " << o << std::endl; 
     std::cout << "Repetitions of u: " << u << std::endl; 

    } 

    else std::cout << "Error in opening file" << std::endl; 

    return 0; 
} 

我試圖做一個簡單的C++程序計算的元音字母出現在一個txt文件,使用Visual Studio 2015 該代碼在調試模式,但是當我沒有調試(從Visual Studio中啓動)它不會打開文件。爲什麼會發生,我該如何解決? TXT文件是在程序的同一目錄爲什麼Visual Studio在「無需調試」模式下打開文件?

當我如使用完整路徑我沒有問題Y:\ Documents \ Visual Studio 2015 \ Projects \ stream \ stream \ myfile.txt但是我想知道爲什麼它不適用於相對路徑,例如myfile.txt的

謝謝!

+0

該文本文件在_Debug_文件夾中是不是? –

+0

它應該與項目文件位於同一文件夾中,除非更改了項目的設置。 – drescherjm

+0

在MSVS中,文本文件需要位於源文件的相同位置。你的文本文件在哪裏? – NathanOliver

回答

0

的Visual Studio改變程序的「工作目錄」,這取決於你如何執行它。如果您從Visual Studio IDE中運行它,默認情況下它將使用源目錄作爲其工作目錄(這可以在項目屬性中進行更改)。如果你不這樣做,程序將使用程序執行的目錄。

爲了安全起見,你可以嘗試保留兩個源目錄和目標目錄(可執行文件被創建)的文件的副本,以確保它沒有任何麻煩找到它。

+0

@AnT編輯回答以反映該信息。 – Xirema

+0

我複製我的文件在目標目錄(其中有.exe),但我仍然有同樣的問題..什麼是源目錄?哪裏也有.vcxproj文件?如果是這樣,myfile.txt也已經存在。 有沒有辦法在「無需調試模式下啓動」中選擇工作目錄? 感謝您的回答! – Ale

+0

@Ale「源目錄」是您的.h和.cpp文件(通常位於)的位置。如果您將目錄結構的屏幕截圖添加到問題中,可能會有所幫助,以便我們瞭解事情的佈局以及尋找差異。 – Xirema

相關問題