2017-02-09 59 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); 

这消除了错误,你的代码的工作,因为它应该。

相关问题