关于在C++中访问字符串字母
Regarding accessing letters of strings in C++
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;cin>>n;//entering number of string to be inputed
string a[n];//declaring an array of type string
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=0;i<n;i++){
cout<<a[i]<<endl;
}
//for manipulating letters of strings
cout<<a[0][1];
return 0;
}
要访问字符串的元素,我们应该将结果输出为多维数组。这似乎有点违反直觉。有人可以解释这是正确的方式吗?
Input
2
asfdsf
asfdsafd
Output
asfdsf
asfdsafd
s
字符串是一个字符数组。 因此,字符串数组是字符数组的数组。 要访问第 i
个字符串中的第 j
个字符,请使用 a[i][j]
。
您不能声明:
string a[n]; //declaring an array of type string
为什么?
ISO C++ forbids variable length array ‘a’
相反,您应该使用string
vector
并.push_back()
您添加的每个新字符串,例如
#include <iostream>
#include <string>
#include <vector>
int main (void) {
int n = 0;
std::cout << "enter the number of strings: ";
std::cin >> n;
if (n < 1) {
std::cerr << "error: invalid number of strings.n";
return 1;
}
std::vector <std::string> a; // vector of strings
for (int i = 0; i < n; i++) { /* read each string */
std::string tmp;
std::cin >> tmp; /* into a temp string */
if (!std::cin.eof() && !std::cin.fail()) /* validate read */
a.push_back(tmp); /* add string to vector */
/* output string and first character using indexes */
std::cout << "string[" << i << "]: " << a[i] << " (a[" << i
<< "][0]: " << a[i][0] << ")n";
}
}
示例使用/输出
$ ./bin/stringindex
enter the number of strings: 4
My
string[0]: My (a[0][0]: M)
Dog
string[1]: Dog (a[1][0]: D)
Has
string[2]: Has (a[2][0]: H)
Fleas!
string[3]: Fleas! (a[3][0]: F)
仔细看看,如果您有任何问题,请告诉我。
相关文章:
- 为什么没有访问所有字符串字符?
- 使用 ReadProcessMemory 获取字符串值的访问冲突
- 循环访问还包含未使用元素的字符串数组
- 循环访问资源字符串表
- 在qt创建器中调试时如何访问字符串变量的完整值?
- 当我用"ñ"字符循环访问字符串时出现奇怪的结果
- 如何在读取文件时访问以前的字符串?
- C++字符串问题-如何访问字符串元素
- 访问包含P的有效索引时返回空格的C++字符串
- 交换两个字符串时访问正确的内存时,我遇到了分段错误
- C++/CLI访问字符串::来自非CLI代码的格式
- 需要从字符串数组的一部分访问元素
- 是否可以从字符串访问变量?
- 循环访问 c++ 中的字符串
- 循环访问字符串片段
- 如何修复访问动态数组中结构中的字符串变量时"segmentation fault (core dumped)"错误
- 如何在 Qt/C++ 中仅将文件路径作为字符串访问文件
- C 使用字符串访问变量
- 基于字符串访问类成员
- 动态 C 字符串访问