2017-02-09 63 views
2

目標:用C++編寫程序如何將整行作爲輸入到一個字符串變量後採取雙作爲輸入?

1.聲明變量:一個double類型,以及一個String類型。

2.將雙倍變量的總和打印到新行上的小數點後一位。

3.將您作爲輸入讀取的字符串連接在一起並將結果打印在新行中。 (完成這個程序)

int main() 
{ 

double d = 4.0; 
string s = "hello and welcome "; 

//write ur code here 
// double variable 
//string variable 
//i/p double from user 
// i/p string from user 
// print sum of double 
// print concatenated string 

}

樣品I/P = --- 4.0 umang馬漢特!

sample o/p ---- 8.0 hello and welcome umang mahant!

//this is my code but it isnt taking the line as input i really dont know why? 
    #include <iostream> 
    #include <iomanip> 
    #include <limits> 

    using namespace std; 

    int main() { 
    double d = 4.0; 
    string s = "hello and welcome "; 
    double b; 
    string s2; 
    cin>>b; 
    getline(cin, s2, '\n'); 
    cout<<d+b<<"\n"; 
    cout<<s<<s2<<"\n"; 
    } 
+0

1)如果該字符串不存在於代碼中,也不在代碼輸入中,您將如何期望代碼輸出「hello and welcome」。 2)難道你不能定義你的意思是什麼_不把這行作爲input_?因爲它[以整行爲輸入](http://ideone.com/nN6W2Q)。 –

+0

@Umang來自浦那的Mahant .Hi。將它們打印在一起並不是連接!你需要使用內置的函數:)並且只需要改變getline函數,就像忙碌的程序員所建議的那樣 – minigeek

+0

@minigeek我是一個初學者...我只需要將它們打印在一起。 –

回答

1

首先改變s到

s = "hello and welcome" 

然後看看下面的代碼

#include <strtk.hpp> 

double sum = d + b ; // adding doubles 

std::string sum_as_string = strtk::type_to_string<double>(sum); //converted sum to string 

std::string final_string = sum_as_string + s2 + s;//concatenate your input string to sum string and s string 

現在打印final_string。

(你不是串聯實時字符串,數字印刷在一起是不是一個解決方案!) getline(cin, s2)後插入這個代碼,並刪除2條COUT語句,然後在最後寫

cout<<final_string<<"\n"; 

如果你不想來連接那麼你可以正確的輸入函數getline

回答您的hackerrank挑戰

int p; 
double q; 
string s2,result; 

// Declare second integer, double, and String variables. 

// Read and save an integer, double, and String to your variables. 
cin>>p; 
cin>>q; 
getline(cin >> ws ,s2); 

// Note: If you have trouble reading the entire string, please go back and review the Tutorial closely. 

// Print the sum of both integer variables on a new line. 
cout<<p+i<<"\n"; 


// Print the sum of the double variables on a new line. 
std::cout << std::fixed; 
std::cout << std::setprecision(1); 
cout<<q+d<<"\n"; 
// Concatenate and print the String variables on a new line 
result = s + s2; 
cout<<result<<"\n"; 
+0

請轉到此鏈接。 https://www.hackerrank.com/challenges/30-data-types,因爲我不能在這challange包括頭flie可以我們有另一種方法來解決它? –

+0

是的,我們做,檢查編輯 – minigeek

+0

而且它只是hackerrank字符串在挑戰不是你好,歡迎 – minigeek

0

我假設你張貼的所有樣品的輸入和輸出下面的代碼是你問的人。

問題在於你的getline()函數。爲什麼你在這個函數中有3個參數?它產生一個錯誤。你應該改變你的函數getline()語句:

getline(cin, s2); 

這消除了錯誤,你的代碼的工作,因爲它應該。

相關問題