输出
1.浮点输出
printf_s("%.1f", 8.0/5.0);
// "%.lf": 保留一位小数 有小数点
printf_s("%lf", 8.0/5.0);
// "%lf": 输出浮点数
2.输入字符串
例:输出字符串中不重复的字母
输入:I am happy!
输出: I amhpy!
分析:如果使用cin 和 scanf 都会导致在I处停止。这里使用getchar()函数一个一个字符开始读,然后每读一个字符就处理一个字符。
#include<iostream>
#include<string>
#include<cstdio>
#include<set>
#include<cstring>
using namespace std;
int main()
{
int c, q = 1;
set<char> st;
string ans = "";
while ((c = getchar()) != '\n' )//如果输入的不是换行
{
if (st.count(c) == 0) {
st.insert(c);
ans.push_back(c);
}
}
cout << ans << endl;
return 0;
}
多行输入,但是不提前告诉你输入多少个字符串,方案一与EOF判断
#include<iostream>
#include<string>
#include<stack>
#include<cstdio>
#include<set>
#include<cstring>
using namespace std;
int main()
{
int c, q = 1;
set<char> st;
string ans = "";
while ((c = getchar()) != EOF)//不等于文件末尾
{
/*if (st.count(c) == 0) {
st.insert(c);
ans.push_back(c);
}*/
ans.push_back(c);
if (c == '\n') {
cout << ans << endl;
ans.clear();
}
}
return 0;
}
如果没有空格使用 scanf().scanf 的返回值代表成功读取了多少个值。
scanf("%d %d",&a,&b); //成功返回2
#include<iostream>
#include<string>
#include<stack>
#include<cstdio>
#include<set>
#include<cstring>
using namespace std;
int main()
{
set<char> st;
string ans = "";
char s[30];
int i = scanf("%s", s);
cout << i << endl;
while (scanf("%s", s) == 1)
{
printf("%s\n", s);
}
//cout << ans << endl;
return 0;
}
#include <iostream>
#include <cstdio>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string line;
while(getline(cin, line))
{
int sum =0, x;
stringstream ss(line);
while(ss >> x) sum+=x;
cout<< sum << "\n";
}
return 0;
}
牛客网在线OJ训练
https://ac.nowcoder.com/acm/contest/5650/A
#include <cstdio>
int main()
{
int a,b;
while(scanf("%d %d",&a,&b)== 2){
printf("%d\n", a+b);
}
return 0;
}