553C++笔试笔记2016

目录

1.输入一行文本,求文本中每个单词的长度。

方法1

方法2


1.输入一行文本,求文本中每个单词的长度。

方法1


#include <string>
#include <iostream>
#include <iomanip>
using namespace std;

string a;
int main() {
	/*getline(cin, a);*/
	cin >> a;
	string word;
	cout << setw(6) << "word" << setw(8) << "length" << endl;
	while(!a.empty()){
		/*if (a.find(" ") == a.npos) {
				word = a.substr();
				cout << setw(6) << word << setw(8) << word.length() << endl;
				break;
		}*/
		word = a.substr(0, a.find(" "));
		cout << setw(6) << word << setw(8) << word.length() << endl;
		a.erase(0, a.find(" ") + 1);
	}
	return 0;
}

上面代码里有个问题,cin遇到空格是会结束的,所以应该用注释里的getline()。

这里遇到了几个问题,比较初级,但是还是记录一下。

1.c++中的cin用法

接受字符或者数字,如果接收对象是字符串,遇到空格、TAB和回车就结束。

如果需要输入带有空格等的字符串,就需要用到cin.getline();

#include <iostream>
using namespace std;
main ()
{
	char m[20];
	cin.getline(m,5);
	cout<<m<<endl;
}
injkl
injk

需要注意的是cin.getline实际上有三个变量为(字符串变量,字符个数,结束字符),其中第三个参数默认为‘\0’。

如果将上述代码稍作修改,有:

#include <iostream>
using namespace std;
int main()
{
	char m[20];
	cin.getline(m, 5,'a');
	cout << m << endl;
}
cha
ch

输出到终止符a就结束了

2.c++中的getline()

作用为接收一个字符串,直接上代码

#include<iostream>
#include<string>
using namespace std;
main ()
{
	string str;
	getline(cin,str);
	cout<<str<<endl;
}

wo ai ni
wo ai ni

这边唯一需要注意的是需要包含string

方法2


#include <string>
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
	
	
	char* t = NULL;
	char a[20];
	gets_s(a);
	puts(a);
	cout << setw(6) << "word" << setw(8) << "length" << endl;
	char* s = strtok_s(a, " ", &t);
	while (s) {
		cout << setw(6) << s << setw(8) << strlen(s) << endl;
		s = strtok_s(NULL, " ", &t);
	}
	return 0;
}
	

strtok的这种循环结构需要记住:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
 
int main()
{
	char string[] = "A string\tof ,,tokens\nand some  more tokens";
	char seps[] = " ,\t\n";
	char *token = NULL;
	printf("Tokens:\n");
	char* ptr = NULL;
	token = strtok_s(string, seps, &ptr);//相较于strtok()函数,strtok_s函数需要用户传入一个指针,用于函数内部判断从哪里开始处理字符串
	while (token != NULL) {
		printf("%s\n", token);
		token = strtok_s(NULL, seps, &ptr);//其他的使用与strtok()函数相同
	}
	return 0;
}
Tokens:
A
string
of
tokens
and
some
more
tokens

seps存储了一些非单词的字符,用strtok去除

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值