C ++帮助创建一个字符串程序 [英] C++ help creating a string program

查看:79
本文介绍了C ++帮助创建一个字符串程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个程序对我来说甚至不能测试SSAN 。我做错了什么?

This program does not work enough for me to even test just the SSAN. What am I doing wrong?

/***************************************************
DESCRIPTION: Ch 7 Exercise 8 on page 504
			This program will read a student's
			name, social security number, user ID,
			and password then displays the SSAN and
			password as X's. 
***************************************************/

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string studentInfo;
	int pos = 0;

	cout << "Enter a student's name, soical security number, "
		<< "\nuser ID, and passwaord in one line. " << endl;
	getline(cin, studentInfo);
	cout << endl;

	//code to replace digits in SSAN with 'X'
	for (int i = 0; i < 9; i++)
	{
		pos = studentInfo.find_first_of("0123456789", pos);
		studentInfo.replace(pos, 1, "X");
	}
	//pos = studentInfo.find_first_not_of("0123456789", pos +1);
	//or
	pos = studentInfo.find(" ", pos); //after the SSAN 
	pos = studentInfo.find(" ", pos + 1); //after user ID

	for (int i = 0; i < studentInfo.length() - pos; i++)//number of characters to replace
	{
		studentInfo.replace(pos + i, 1, "X");
	}
	
	//code to position the index at the password

	//code to replace password with 'X'es
	for (int i = 0; i < studentInfo.length(); i++)
	{
		pos = studentInfo.find_last_of("0123456789", pos);
		studentInfo.replace(pos, 1, "X");
	}
	

	system("pause");
}

推荐答案

Quote:

首先,确保您在SSAN,用户名和密码中使用的格式与您在代码中搜索的格式字符串相匹配。



例如,您在给定输入中使用了0123456789的出现。

如果这是正确的,则字符串函数find_first_of ()和find_last_of()将为您找到找到此字符串的正确位置。在这种情况下你不会得到任何运行时错误。



再次,用X替换密码字符,你正在搜索0123456789。这是不正确的,因为我们通常使用字母数字字符作为密码,您应该只指向第二个空格的末尾以知道密码的起始位置。

否则,您将获得pos值为-1,基于此,find_last_of()将崩溃。

First, make sure the format you use for the SSAN, Username and Password matches the format string which you are trying to search for, in your code.

For example, you were using the occurrence of "0123456789" in the given input.
If that is right, the string functions find_first_of( ) and find_last_of( ) will give you correct position where this string occurrence is found. You will not get any runtime errors in that case.

Again, for replacing the Password characters with "X", you're searching for "0123456789". This is not correct, since we usually use the alphanumeric characters for the password, and you should just point to the end of second " " space to know where your password starts from.
Otherwise, you will get pos value as "-1" based on which, the find_last_of( ) will crash.


您应该首先分隔不同的字段(例如使用空格作为分隔符)和然后在正确的字符串上应用所需的替换。
You should first separate the different fields (for instance using the blank as separator) and then apply the required replacements on the proper strings.


这篇关于C ++帮助创建一个字符串程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆