2016-10-22 25 views
1
#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 
#include <cstring> 


using namespace std; 

int StrInt(int x,string y) 
{ 

    return y.at(x); 
    cout << y.at(x) << "hallo"; 
} 
int Get_Int(int linie, int zeichen){ 
    ifstream file; 
     string line; 
     vector<string>lines; 
     file.open("C:/Soi/input/input.txt"); 
     if(file.is_open()) 
     { 
      cout << "file is open" << endl; 
      int x = 0; 
      lines.resize(1); 
      while(getline(file, line)) 
      { 
       lines[x] = line; 
       lines.push_back(line); 
       x++; 
       cout << lines[x] ; 

      } 
      lines.erase (lines.begin()+x); 
      cout << endl; 

     } 
     else{ 
      cerr<<"file could not be opened!"; 

     } 
     for(unsigned int i = 0; i < lines.size(); i++) 
     { 
       cout << lines[i] << " /" << i << endl; 
     } 
     string hh = lines[linie]; 
     cout << hh.at(zeichen) << " hallo" << endl; 
     cout << "returned value: " << hh.at(zeichen) << endl; 
     return hh.at(zeichen); 

} 


int main() { 
    cout << "Programm gestartet" << endl; 
    int zeichen = 0; 
    int linie = 0; 
    int resultat = Get_Int(linie, zeichen); 
    int opperand1 = 2; 
    int opperand2 = 48; 


    if (opperand1 + opperand2 == resultat){ 
     cout << resultat << endl << "true" ; 
     return 0; 
    } 
    else{ 
     cout << resultat << endl; 
     return 0; 
    } 

    return 0; 
} 

im試圖得到的正常值是:3 代碼還沒有完成。我試圖打印出來後,如果這兩個值就像結果一樣,後面的 。 我試着在代碼中進行一些更改,但它沒有奏效。 值,即IM從我的函數返回一個錯誤的值C++

COUT < < hh.at得到(賊臣)

爲與值不同,IM是從

越來越COUT < < resultat

非常感謝你太多

對不起我的英語不好。

回答

2

你的函數聲明爲返回int,但返回的是:

string hh = lines[linie]; 
    /*...*/ 
    return hh.at(zeichen); 

的問題是,string::at返回char&char小號愉快地轉換爲int沒有問題,但你不會得到的結果你的期望。你必須解析數,即是這樣的:

return hh.at(zeichen) - '0'; 
1

hh.at(zeichen)zeichen位置從字符串hh的字符。該類型是char &

當您用cout << hh.at(zeichen)打印該字符時,將打印該字符,例如'0'。

int Get_Int(int linie, int zeichen) { 
    ... 
    return hh.at(zeichen); 
} 

int result = Get_Int(linie, zeichen); 

在這個函數返回的字符,但是編譯器需要將其轉換爲int。現在重要的是如何存儲char以及它具有的值。 char只包含(通常)一個字節長度的數字。如何解釋這些取決於系統。對於當前的PC,字符通常以ASCII碼形式存儲。 '0'有ASCII碼48.

當你打印一個char時,你會得到用相同的ASCII碼(代碼48,char'0')打印的字符。如果您打印一個int,例如result,您將得到打印的數字(首先轉換爲字符串,然後打印;數字48,字符串「48」)。

您可以打印(char)result,這會將int轉換回,其中cout將打印爲字符。或者,您可以將char轉換爲char中字符所表示的數字。在ASCII編碼的情況下,如果您確定所有字符都代表數字,您可以減去hh.at(zeichen) - '0',其中0代表'0',1代表'1',依此類推。但是你應該記住,這隻適用於像ASCII和EBCDIC這樣的字符表示,其中'0'到'9'由字符代碼表示,它們都是相鄰的,並且與數字的順序相同。