c++ - Count a string from 1 instead of 0 in c++
问题描述
do you know how can I start to count a string from 1 and not from 0 in c++? for example, xyz are on iterations 0,1,2.. but i need them to be on 1,2,3. I know you can put cout << i+1; but is there any other way to do this with strlen(s+1)?
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[100];
cin.getline(s, 99);
int n = strlen(s);
for (int i = 0; i < n; ++i)
cout<<i<<": "<<s[i]<<"\n";
return 0;
}
解决方案
在 C++ 中,您不应该使用 C 字符串。相反,使用 std::string:
#include <iostream>
#include <string>
int main()
{
std::string s;
std::getline(std::cin, s);
for (int i = 0; i < s.length(); ++i)
std::cout << i + 1 << ": " << s[i] << '\n' ;
return 0;
}
推荐阅读
- r - Weekly aggregation of dataframe by category
- php - 如何通过textview中表的primery key从android中的PHP服务器检索数据
- python - 有没有办法将 Python f-string 支持添加到 Visual Studio 2017?
- r - 将鼠标悬停在分类轴上
- javascript - Close div with click outside (parent)
- android - 如何在progressDialog android中居中标题?
- javascript - 在浏览器中重新打开最近的选项卡时如何清除会话
- c++ - 包含犰狳库时的视觉c ++ min max警告
- python - Edit specific line at specific position in Text file in Python
- java - Running a process inside a folder on Linux in Java