如何从输入字符串中提取特定位置的字符?
How do I extract characters in a specific position from an input string?
对于我的家庭作业项目,我应该创建一个程序,询问用户他们最喜欢的城市以及他们想要显示哪个角色。用户输入一个数字,表示他们想要显示的城市中字符的位置,程序应该在此位置显示字母。
我们还没有学会如何从字符串中提取字符,但我们项目的这一部分应该表明我们可以正确地谷歌来找到我们的编码解决方案。我找到了一个 void 函数,可以为我从特定位置提取角色,但完全不知道如何使用它。我已经尝试了几种不同的方法,并输入了我可能想到的所有方法来实现此功能,但它没有奏效。
我尝试完全按原样复制我在网上找到的示例代码(在此地址找到的第一个示例:https://www.geeksforgeeks.org/string-at-in-cpp/(,但即使是该示例也无法在 Visual Studio 2017 中运行。
#include <iostream>
#include <string>
using namespace std;
void at(string);
int main()
{
//variables for favorite city & display character
string favCity;
int dispChar;
//asking user for favorite city
cout << "Input your favorite city: ";
cin >> favCity;
cout << "Which character would you like to display: ";
cin >> dispChar;
cout << endl << endl;
cout << "The user entered: " << favCity << endl;
cout << "The character at position " << dispChar << " is: " << at();
}
预期结果是计算机将显示"位置 (dispChar( 处的字符为:(无论用户输入位置 dispChar 处的任何字母(">
例如:"The character at position 2 is: e
//如果用户输入城市底特律
我收到错误at
未定义,当我尝试使用str.at();
时,我会得到str
未定义,等等。
无需使用外部函数即可通过索引从字符串中提取字符。std::string
本身实现了std::string::at
函数,也重载了[]
运算符。
所以有两种方法可以做到这一点:
1.
cout << "The character at position " << dispChar << " is: " << favCity.at(dispChar);
阿拉伯数字。
cout << "The character at position " << dispChar << " is: " << favCity[dispChar];
std::string::at 可用于从给定字符串中提取字符。char& string::at (size_type idx)
字符串::at 函数返回特定位置 (idx( 处的字符。您可以直接使用 string::at 作为包含类的。在此处了解更多信息
因此,在您的解决方案中,您声明了void at(string);
因此您也需要定义它。 我已经对您的代码进行了一些更改,我认为应该这样做。
#include <string>
using namespace std;
void extract_char(string str, int pos)
{
cout<<str.at(pos);
}
int main(void)
{
int dispChar;
string favCity;
cout<<"Input your favorite city: ";
cin>>favCity;
cout<<"Which position would you like to extract the character from(0 to size of city): ";
cin>>dispChar;
cout<<endl<<endl;
cout<<"The user entered: "<<favCity<<endl;
extract_char(favCity, dispChar-1);
/*
OR
cout<<"The character at position "<<dispChar<<" is: "<<favCity.at(dispChar-1);
*/
return 0;
}
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 无法获取webot::PositionSensor对象中位置传感器的值
- 非常量变量只读位置的赋值
- 如何定义更改car类中car位置的方法
- 使用迭代器时如何访问对象在向量中的位置?
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 求最大元素位置的分治算法
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 是与初始类同一内存位置的重新定位类
- 如何在使用网格布局时重叠qwidgets,并将重叠的widget定位在距离窗口边界特定距离的位置
- 我不知道如何定位最高随机数的位置
- 如何在MFC上设置窗口位置以将其定位到屏幕顶部
- 将QGraphicsSvgItem的中心定位在一个位置上。
- 如何定位WinRT异步方法调用中出现错误的位置
- 重定位表项在平面二进制文件中的存储位置