首页 > 解决方案 > 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++ 中,您不应该使用 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;
}

推荐阅读